我有一个jQuery函数,可以从列表中添加和删除产品。
$("#basketItemsWrap li img").live("click", function (event) {
$("#notificationsLoader").html('<img src="http://images/loader.gif">');
var oid = $("#thelist li").attr('id').split('_')[1];
$.ajax({
type: "POST",
url: "http://index.php/action/delete",
data: {
officeID: oid,
action: "delete"
},
success: function (theResponse) {
$("#officeID_" + oid).hide("slow", function () {
$(this).remove();
});
$("#notificationsLoader").empty();
}
});
});
My HTML code
<div id="basketItemsWrap">
<ul id="thelist">
<li></li>
<?php echo getBasket(); ?>
</ul>
</div>
html输出为
<li id="officeID_15669">Office 1</li>
<li id="officeID_14903">Office</l 2i>
我想从<li>
分裂中获得id并获得数字,以便我可以将值传递给数据库。
var oid = $("#thelist li").attr('id').split('_')[1];
当我点击时,oid
总是未定义的。我的代码中有什么错误?
$("#thelist li")
选择#thelist中的所有列表元素,第一个是<li></li>
。attr('id')
应用于第一个,因此未定义。
在click处理程序中使用:
var oid = $(this).parent("li").attr('id').split('_')[1];
我希望这对你有帮助:
$("#basketItemsWrap li img").on("click", function(event) {
$("#notificationsLoader").html('<img src="http://images/loader.gif">');
var attrid = $(this).parent().attr('id');
var oid = attrid.split('_')[1]);
$.ajax({
type: "POST",
url: "http://index.php/action/delete",
data: {officeID: oid, action: "delete"},
success: function(theResponse) {
$("#officeID_" + oid).hide("slow", function() {$(this).remove();});
$("#notificationsLoader").empty();
}
});
});
我为您创建了一个实时示例(但没有ajax函数):
http://jsbin.com/ozepoh/2/
当你使用var oid = $("#thelist li").attr('id').split('_')[1];
时,它总是得到列表中第一个li
的id
,而不是点击li
的id
。
您可以使用$(this).parent()
获得点击的li
。
$("#basketItemsWrap").live("click", 'li img', function (event) {
$("#notificationsLoader").html('<img src="http://images/loader.gif">');
var oid = $(this).parent().attr('id').split('_')[1];
$.ajax({
type: "POST",
url: "http://index.php/action/delete",
data: {
officeID: oid,
action: "delete"
},
success: function (theResponse) {
$("#officeID_" + oid).hide("slow", function () {
$(this).remove();
});
$("#notificationsLoader").empty();
}
});
});
未定义,因为粗体
<div id="basketItemsWrap">
<ul id="thelist">
**<li></li>**
<?php echo getBasket(); ?>
</ul>
</div>
因为它没有id属性所以$("#thelist li")选择这个然后$("#thelist li")。attr(" id ")导致undefined