如何使按钮在JQuery中的项目上正确排序?
问题描述:
我有一个JQuery可排序,每个项目包含一个按钮。在页面顶部,我有一个添加按钮,将项目添加到可排序的项目中。我正尝试对每个可排序的按钮进行编程,以用自动完成(也在页面顶部)中的当前用户输入值替换该特定项目上的字符串。这里是我的代码:如何使按钮在JQuery中的项目上正确排序?
$(".addButton").click(function(e) {
e.preventDefault();
// set var item to be the string inputted by the user
var item = $("input[name='inputItem']").val(); //where 'inputItem' is the name of the <input>
// parses input string, splitting at commas into liArray containing substrings as elements
var liArray = item.split(", ");
// for loop to add each brew to the sortable list (length-1 because last element in array is empty string)
for (var i = 0; i < liArray.length-1; i++) {
// sets var $li to the string in the ith index of liArray
var $li = $("<li class='ui-state-default'/>").text(liArray[i]).append('<button class="replaceButton">Replace</button>');
// adds var $li to gui
$("#sortable").append($li);
};
$("#sortable").sort();
// refreshes the page so var $li shows up
$("#sortable").sortable("refresh");
});
现在,我每一个新增项目有一个按钮带class =“replaceButton”,我以为我可以在我的.js只是声明是这样的:
$(".replaceButton").click(function() {
// set var item to be the string inputted by the user
var item = $("input[name='inputItem']").val(); //where 'inputItem' is the name of the <input>
// I DON'T KNOW WHAT TO DO HERE
});
我不知道从哪里去那里,因为我不知道如何访问特定项目的字符串。我会用“这个”吗?也不是简单的替换字符串,我删除了特定的项目,并在它的位置创建了一个新的项目?感谢您的任何建议或答案!
答
因为你知道你的按钮是你li
的一部分,您可以访问文本那样:
// mind the dynamic event binding!
$('#sortable').on('click', ".replaceButton", function(e) {
e.preventDefault();
var item = $("input[name='inputItem']").val();
$(this).parent()
.text(item)
.append($(this).clone());
});
你将不得不追加的replaceButton的另一个实例,当你想保留它。
而且由于您动态添加按钮,因此请注意事件绑定中的更改。我将click事件绑定到一个持久的容器,并且动态绑定到.replaceButton
的所有实例,即使它们不存在。
所以你试图访问最近添加的列表项? –
不一定,用户将在由“,”分隔的自动完成中输入4个名称的字符串。然后用户将点击'ADD'按钮,将4个子字符串放入它们自己的(总共4个)可排序的项目中。然后用户将删除自动填充并放入一个名称。我希望用户能够点击排序中的“REPLACE”按钮之一,该特定项目将被替换为自动完成中的名称。 – sbru
你可以发布标记吗? –