对于这个问题来说,这不是一个很好的标题,所以如果其他人在阅读之后有更好的方式来表达它,那就不胜感激了。
披露信息,这是功课。本周的任务是重构我们已经存在的普通JS代码以使用JQM,我遇到了转换的问题,我无法弄清楚,这是代码:
function populateItemLinks(key, listItem)
{
var ecLink = $('<a class="padRightRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Edit Character");
ecLink.on("click", editCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
ecLink = $('<a class="padLeftRed"></a>');
ecLink.attr("href", "#");
ecLink.attr("key", key);
ecLink.html("Delete Character");
ecLink.on("click", deleteCharacter);
ecLink.appendTo(listItem);
console.log(ecLink.attr("key"));
};
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
console.log(this.key);
alert("Character was deleted.");
localStorage.removeItem(this.key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
问题是使用.key属性作为populateItemLinks函数中链接的标记。当它是strait javascript时,我可以做linkname.key = key;然后使用“this.key”将密钥返回到deleteCharacter函数中。好吧,现在它总是返回undefined,我想不出任何方式来解决与非JQM版本相同的功能,所以任何帮助都会受到赞赏。
答案 0 :(得分:1)
您的代码未定义返回的原因是您尝试读取DOM元素的属性,但是您已经设置了DOM元素的属性
这个问题的最佳答案解释了两者之间的差异:.prop() vs .attr()
如果您要设置新创建的DOM元素的属性,请执行以下操作:
ecLink.prop('key', 12355);
继续直接访问DOM元素(不是通过jQuery):
this.key; // 123455
一切都很好。这是一个 JSFiddle example ,更详细地说明了这一点。
无论如何,我已调整您的代码以使用您正在设置的属性:
function deleteCharacter()
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = $(this).attr('key');
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}
说完这一切之后,Data attributes更适合存储针对DOM元素的任意数据:
ecLink.data('key', myKey); // set
ecLink.data('key'); // get
答案 1 :(得分:0)
我要做的是将点击的ecLink
作为参数传递给deleteCharacter()
,如下所示:
ecLink.on("click",function() { deleteCharacter($(this)); });
然后您可以修改deleteCharacter()
:
function deleteCharacter(el)
{
var toDelete = confirm("Do you wish to delete this character?");
if (toDelete)
{
var key = el.attr('key'); //get the key attribute
console.log(key);
alert("Character was deleted.");
localStorage.removeItem(key);
$.mobile.changePage("#home");
}
else
{
alert("Character was not deleted.");
}
}