代码之家  ›  专栏  ›  技术社区  ›  H.Epstein

jQuery链接列表

  •  -1
  • H.Epstein  · 技术社区  · 7 年前

    我的代码是:

    sections.forEach(sec => {
       var li = jQuery(`<a href='/dish.html'><li>${sec.sectionName}</li></a>`)
       jQuery('#sections').append(li);
         });
     jQuery('#sections').click(function() {
        //here I need to determine what link was pressed by the user.
            });
    
    
    #sections is an ordered list
    

    谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rahul Pawar    7 年前

    你可以这样做。我不知道你要从哪些数据中提取 <li> . 我已经提取了 < 希望对你有帮助。

    var sections = [{"sectionName":"rahul"},{"sectionName":"rohit"}]; // My dummy Object
    
    sections.forEach(sec => {
       var li = jQuery(`<a class="mylinks" href='#'><li>${sec.sectionName}</li></a>`)
                jQuery('#sections').append(li);
          });
    
    $(document).on("click",".mylinks",function(){
      var  touched_li = $(this).find("li").text();
      alert(touched_li); // Get section name. e.g rahul
    });
    
        2
  •  1
  •   lukbrt    7 年前

    您可以为每个“li”元素附加动作侦听器,而不是确定按下了哪个链接。 顺便说一句,当您将任何DOM元素赋给变量名时,在变量名的开头加上“$”符号是一种惯例(这就是我这样做的原因)。

    sections.forEach(sec => {
        var $li = jQuery(`<a href='/dish.html'><li>${sec.sectionName}</li></a>`);
        $li.on('click', () => {
            //here you can attach listener for each element. You can reference using:
            var $currentElement = $(this);
            //now you can operate on current anchor element.
        });
    
        jQuery('#sections').append($li);
    });
    
    推荐文章