gpt4 book ai didi

javascript - 动态更改后不应用功能

转载 作者:行者123 更新时间:2023-11-30 14:57:44 24 4
gpt4 key购买 nike

var lootis = $('div > span');
var loot = 0

function loots() {
lootis.each(function(e) {
$(this).toggle(e >= loot && e < loot + 1);
});
}
loots();

$('div').on('click', 'span', function(){
loot = loot + 1;
loots();
});

//Problem Starts Here:
$('div').on('contextmenu', 'span', function(){
$('div').html('<span>Loot4</span> <span>Loot5</span> <span>Loot6</span>');
loots();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>Loot1</span>
<span>Loot2</span>
<span>Loot3</span>
</div>

您好,我这里有这段代码,点击跨度会更改为下一个跨度

右键点击 span 变为 4 5 6,但是函数 loots() 不适用于它们,它应该是 1 2 3,每次点击只出现一个 span,这是什么问题在代码中?

最佳答案

On right-click the spans changes to 4 5 6, But the function loots() doesn't apply on them

您在 JS 代码的开头获取一次 dom 元素:

var lootis = $('div > span');

但是当您更改 <div> 的 innerHTML 时:

$('div').html('<span>Loot4</span> <span>Loot5</span> <span>Loot6</span>');

lootis仍然指的是旧元素而不是新元素。您需要做的就是从 dom 中重新获取元素:

(function() {

var lootis = $('div > span');
var loot = 0

function loots() {
lootis.each(function(e) {
$(this).toggle(e >= loot && e < loot + 1);
});
}
loots();

$('div').on('click', 'span', function() {;
loot = loot + 1;
loots();
console.log("click");
});

//Problem Starts Here:
$('div').on('contextmenu', 'span', function() {
$('div').html('<span>Loot4</span> <span>Loot5</span> <span>Loot6</span>');
lootis = $('div > span'); //getting the new spans in the changed div
});

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
<span>Loot1</span>
<span>Loot2</span>
<span>Loot3</span>
</div>

关于javascript - 动态更改后不应用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46992803/

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