gpt4 book ai didi

jQuery click 函数与内联 onclick

转载 作者:行者123 更新时间:2023-12-03 22:20:05 27 4
gpt4 key购买 nike

我正在尝试重新组织我的代码并使其更加不引人注目。

主要是有一个执行操作的链接。如果单击链接,操作将通过 ajax 执行(ajax 代码不在此处的代码中),并且文本将被其他文本替换,为用户提供撤消操作的能力。如果用户单击“撤消”链接,ajax 会恢复之前的情况,并且提供用户执行再次显示的操作的文本。

我在一个 html 文件中制作了一个更简单的问题版本(代码如下)。有两段。如果单击第一段的链接(该链接使用内联 onclick 调用),则代码将按预期工作。但是,如果单击第二段的链接,该链接使用 jQuery onclick 函数,则“撤消”链接不起作用,我不明白为什么。

有什么帮助吗?非常感谢!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
$(".add2").click(function(){
var placeId = $(this).parents(".place").attr("id");
$("#" + placeId + " .add2").remove();
$("#" + placeId + " .actions").append("<span class=\"added\">Added!</span> <a class=\"undoadd2\" href=\"#\">Undo</a>");
return false;
})
$(".undoadd2").click(function(){
var placeId = $(this).parents(".place").attr("id");
$("#" + placeId + " .actions").find("span.added, a.add2").remove();
$("#" + placeId + " .actions").append("<a class='add2' onclick='copyPlace(\"" + placeId + "\"); return false;' href='#'>Add place</a>");
return false;
})
});

function addPlace(placeId){
$("#" + placeId + " .add").remove();
$("#" + placeId + " .actions").append("<span class=\"added\">Added!</span> <a class=\"undoadd\" href=\"#\" onclick=\"undoAddPlace('" + placeId + "'); return false;\">Undo</a>");
return false;
}

function undoAddPlace(placeId){
$("#" + placeId + " .actions").find("span.added, a.undoadd").remove();
$("#" + placeId + " .actions").append("<a class='add' onclick='addPlace(\"" + placeId + "\"); return false;' href='#'>Add place</a>");
return false;
}
</script>

</head>
<body id="home">
<div class="place" id="3435910">
<p class="actions"><a href="#" onclick="addPlace('3435910'); return false;" class="add">Add place</a></p>
</div>

<div class="place" id="3435912">
<p class="actions"><a href="#" class="add2">Add place</a></p>
</div>
</body>
</html>

最佳答案

Since you are dynamically adding new items to the DOM, you will have to register the click handler again on the new items.

您可以使用.live为此。

<小时/>

更新

自 jQuery 1.7 起,.on方法是执行此操作的首选方法。

自 jQuery 1.9 起 .live方法已被删除。

关于jQuery click 函数与内联 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/815856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com