通过jquery在两个DOM元素之间进行更改



我正在做一些事情,不太明白为什么不起作用。我正在尝试制作一个在两个dom元素之间切换的按钮。

我唯一的猜测是,它只是更改html客户端并从服务器中提取类信息?

提前感谢

$(document).ready(function(){
$(".a").click(function(){
$(this).parent().html("<span class='b'>toggle down</span>");
});
$(".b").click(function(){
$(this).parent().html("<span class='a'>toggle up</span>");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<span class="toggle">
<span class="a">toggle up</span>
</span>
</body>
</html>

单击.a时,.b作为全新的元素注入DOM。因此,您需要在每次注入.b时声明click事件。

$(document).ready(function(){
let toggleDown;
function toggleUp() {
$(".b").click(function(){
$(this).parent().html("<span class='a'>toggle up</span>");
toggleDown();
});
}
toggleDown = function() {
$(".a").click(function(){
$(this).parent().html("<span class='b'>toggle down</span>");
toggleUp();
});
}

toggleDown();
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<span class="toggle">
<span class="a">toggle up</span>
</span>
</body>
</html>

更新

这里有一个更合适的方法。

$(document).ready(function(){

const a = "<span class='a'>toggle up</span>";
const b = "<span class='b'>toggle down</span>";

$('.toggle').click(function() {
let self = $(this);
const isA = self.children(":first").hasClass('a');
self.html(isA ? b : a);
});

});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<span class="toggle">
<span class="a">toggle up</span>
</span>
</body>
</html>

您可以使用react.js或vue.js来获取声明性方法。目前您正在使用命令式方法。您可以在https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2

最新更新