【问题标题】:Populate list dynamically动态填充列表
【发布时间】:2014-11-20 23:19:54
【问题描述】:

使用来自http://jquerywidgets.com/widgets/fancy-list/的jQuery FancyList

我试图通过代码插入<li>,而不是通过用户点击操作。

我的问题在于this 关键字,特别是以下几行:

    $(".fancy-list-footer .add").click( function() {
        $('.tab-container .user-information .first-name:last').val('').removeClass('placeholder');
        $('.tab-container .user-information .last-name:last').val('').removeClass('placeholder');
        fancyList($(this));
    });

我希望能够传递名字和姓氏,而不必填充文本框 - for 循环可以做到这一点。

我尝试将 fancyList(elem) 函数更改为 fancyList(elem, firstName, lastName),但我似乎无法获得 elem 的正确值 - 我尝试了 var elem = document.getElementByClassName('fancy-list-footer'),因为我认为这就是按钮单击中 $(this) 所指的内容,但这也不起作用。

Codepen:http://codepen.io/anon/pen/vEYaqa?editors=101

任何帮助表示赞赏!

【问题讨论】:

    标签: javascript jquery html jquery-widgets


    【解决方案1】:

    你可以做一个这样的函数来添加一个名字:

    function addToFancyList(first_name, last_name) {
        $('.fancy-list').find(".fancy-list-content-list:last").append("<li><div class='person'><span class = 'first'>" + first_name + "</span><span class = 'last'>" + last_name + "</span></div><div class='clear'></div></li>");
    }
    

    简单地这样称呼它:

    $(function () {
        addToFancyList('Tom', 'Someone');
    });
    

    【讨论】:

      【解决方案2】:

      答案取决于函数本身。这是您发送的链接中的 fancyList 的实现:

              function fancyList(elem) {
      
              var this_parent = elem.parents(".fancy-list");
      
              rel = this_parent.attr("rel");
                      var regex = /(<([^>]+)>)/ig;
      
              first_name = this_parent.find(".fancy-list-footer input#fancy-list-first-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");
              last_name = this_parent.find(".fancy-list-footer input#fancy-list-last-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");
      
              // more lines of code...
      

      但它可以很容易地变成这样:

              function fancyList(elem, first_name, last_name ) {
      
              var this_parent = elem.parents(".fancy-list");
      
              rel = this_parent.attr("rel");
              var regex = /(<([^>]+)>)/ig;
      
              first_name = first_name .replace(/[<\s]/g, "").replace(/[>\s]/g, "");
              last_name = last_name.replace(/[<\s]/g, "").replace(/[>\s]/g, "");
      
              // more lines of code...
      

      这样该函数将更好地满足您的需求,并且不会强迫您生成元素只是为了获取它们的文本值

      【讨论】:

        猜你喜欢
        • 2011-01-13
        • 2011-05-01
        • 2013-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2021-10-29
        相关资源
        最近更新 更多