2014-11-20 94 views
0

使用jQuery FancyList我試圖插入一個<li>通過代碼,而不是由用戶點擊行爲。填充列表從<a href="http://jquerywidgets.com/widgets/fancy-list/" rel="nofollow">http://jquerywidgets.com/widgets/fancy-list/</a></p> <p>動態

我的問題在於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

任何幫助表示讚賞!

回答

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'); 
}); 
0

答案依賴於函數本身。這裏是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... 

這樣的功能將更好地滿足您的需求,並不會強迫你生成元素以獲取文本值

相關問題