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>
你好,我这里有这个代码,点击跨度改为下一个范围
右键单击跨度更改为4 5 6,但函数loots()不适用于它们,它应该像1 2 3,每次单击只出现一个跨度,问题是什么在代码?
答案 0 :(得分:2)
右键单击跨度更改为4 5 6,但函数loots() 不适用于他们
在JS代码的开头有一次dom元素:
var lootis = $('div > span');
但是当你改变<div>
:
$('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>
答案 1 :(得分:0)
试试这个
(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();
});
//Problem Starts Here:
$('div').on('contextmenu', 'span', function(){
$('div').html('<span>Loot4</span> <span>Loot5</span> <span>Loot6</span>');
});
})();
&#13;
<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>
&#13;
答案 2 :(得分:0)
在更改div的html后重新设置变量.........如下所示
$('div').on('contextmenu', 'span', function(){
$('div').html('<span>Loot5</span> <span>Loot6</span><span>Loot7</span>');
lootis = $('div > span');
loot = 0
loots();
});