我有一个按钮<button class="open" id="1">Open</button>
如果我单击该按钮,我希望该按钮转换为<button class="close" id="1">Close</button>
我为它做了一些脚本
下面是脚本:
$(".open").click(function(){
$ths=$(this);
var id=$(this).val();
$.ajax({
type:"POST",
url:"someurl",
dataType: "html",
data:id,
success:function(res){
$thd.html("Open");
$ths.toggleClass("open close");
}
})
});
$(".close").click(function(){
$ths=$(this);
var id=$ths.val();
$.ajax({
type:"POST",
url:"someurl",
dataType: "html",
data:id,
success:function(res){
$ths.html("Close");
$ths.toggleClass("close open");
}
})
});当我尝试时,在第一次单击它时,它将<button class="open" id="1">Open</button>更改为<button class="close" id="1">Close</button>
第二次点击,我希望它回到这个<button class="open" id="1">Open</button>
但它并没有改变到我想要的。它更改为这个<button class="open" id="1">Close</button>它只更改了类,关闭的文本没有打开。
有人能解释一下为什么它不起作用吗?还有如何使按钮更改类和它的文本,哦,是的,这个问题也有一个名字吗?
请提前回答!
发布于 2016-04-07 08:20:26
$(".close")将在DOM中找到元素.close并绑定事件。当您动态地更改元素的类时,当DOM试图查找元素时,元素不在那里。
使用
Event Delegation,事件委托允许我们将单个事件侦听器附加到父元素,该事件侦听器将为匹配选择器的所有后代触发,无论这些后代现在存在还是将来添加。使用.on()而不是click
$(document).on("click", ".open", function() {
$ths = $(this);
var id = $(this).val();
$.ajax({
type: "POST",
url: "someurl",
dataType: "html",
data: id,
success: function(res) {
$ths.html("Open"); //You had a typo here!
$ths.toggleClass("open close");
}
})
});
$(document).on("click", ".close", function() {
$ths = $(this);
var id = $ths.val();
$.ajax({
type: "POST",
url: "someurl",
dataType: "html",
data: id,
success: function(res) {
$ths.html("Close");
$ths.toggleClass("close open");
}
})
});
https://stackoverflow.com/questions/36470422
复制相似问题