这是我的代码,要修改表格单元格的内容,单击兄弟单元格的“打开/关闭”链接。
第一次链接效果很好,但第二次点击时,再次从
开始执行$("a[href*='close']").click(function (event)
即使新链接包含“打开”而不再包含“关闭”字样。
为什么我这样做? 哪个是问题?我该如何解决?
提前致谢!
$(document).ready(function()
{
$("a[href*='close']").click(function (event)
{
event.preventDefault();
var click = $(this);
console.log(click);
var url = click.attr("href");
console.log(url);
var nid = url.split("/")[1];
console.log(nid);
// var url = "close/" + nid;
// console.log(url);
$.get(url, function(data, status)
{
if (data.status == 1)
{
console.log(data.res);
click.text("Open");
var new_url = url.replace("close", "open");
console.log("New Url = " + new_url);
click.attr("href", new_url);
click.parent().prev().text(data.res);
}
else
{
console.log("Error");
}
});
}); // CHIUDE FUNZIONE
$("a[href*='open']").click(function (event)
{
event.preventDefault();
var click2 = $(this);
console.log(click2);
var url = click2.attr("href");
console.log(url);
var nid = url.split("/")[1];
console.log(nid);
// var url = "open/" + nid;
// console.log(url);
$.get(url, function(data, status)
{
if (data.status == 1)
{
console.log(data.res);
click2.text("Close");
var new_url = url.replace("open", "close");
console.log("New Url = " + new_url);
click2.attr("href", new_url);
click2.parent().prev().text(data.res);
}
else
{
console.log("Error");
}
});
}); // CHIUDE FUNZIONE
答案 0 :(得分:1)
正如我在对该问题的评论中所述,您可以使用委托事件绑定而不是杂耍事件绑定,以允许事件仅由您希望它们处理的逻辑处理。
$(document).on('click', 'a[href*="close"]', function (event) {
event.preventDefault();
console.log('close');
event.target.href = '#open';
});
$(document).on('click', 'a[href*="open"]', function (event) {
event.preventDefault();
console.log('open');
event.target.href = '#close';
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#open">Toggle</a>
&#13;