不想在jQuery中多次对按钮执行操作?



我是jQuery的新手,我在练习以下示例时从w3schools学习它,我不明白为什么函数返回的次数如此之多,我单击按钮并且我不知道要做什么操作这意味着一旦我单击按钮,则必须在dom中更改新的文本/Html,但是如果我再次单击该按钮,则无需执行任何操作。我该怎么做?

<!DOCTYPE html>
<html>
<head>
<title>jQuery HTML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text(function(i, origText) {
return "Old text : " + origText + "New text : Hello World (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i, origText) {
return "Old HTML: " + origText + "New HTML : Hello World (index: " + i + ")";
});
});
});
</script>
</head>
<body>
<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>
<button id="btn1">show old/new text</button>
<button id="btn2">show old/new html</button>
</body>
</html>

我再次单击按钮,然后不执行任何操作

从字面上理解这一点(而不是另一个答案,或者将其视为"它给出了相同的价值"(

您可以使用.one,以便"click"事件仅发生一次:

$("#btn").one("click", function() {
console.log("button clicked");
$("#text").text("after");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='text'>before</div>
<button type='button' id='btn'>click</button>

或者,您可以关闭具有相同效果的点击事件

$("#btn").click(function() {
console.log("button clicked");
$(this).off("click");
$("#text").text("after");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='text'>before</div>
<button type='button' id='btn'>click</button>

它追加文本是因为origText参数保存当前值。因此,您可以将New text...附加到每个事件中已有的任何内容中。

要解决此问题,您可以不使用该参数,并将值设置为每次触发事件时返回相同的字符串:

jQuery(function($) {
$("#btn1").click(function() {
$("#test1").text(function(i) {
return 'New text : Hello World (index: ' + i + ')';
});
});

$("#btn2").click(function() {
$("#test2").html(function(i) {
return 'New HTML : Hello World (index: ' + i + ')';
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>
<button id="btn1">show old/new text</button>
<button id="btn2">show old/new html</button>

我还建议不要将W3Schools用于任何事情,因为它们的内容通常已经过时,有时甚至是完全错误的。

也许使用$("#btn1").one('click', function(){...可以解决您的问题

最新更新