全局变量selected
的调用方式类似于this.selected
,并且始终返回正确的值。
但是从动态创建的函数调用时,其返回unknown
onClick: function(val){
for (i = 0; i <
positions[this.selected].SHC.length; i++){
var tag =
positions[this.selected].SHC[i];
var tagEl =
document.createElement('p');
console.log(this.selected) // RETURNS CORRECT VALUE
tagEl.onclick = function(){
console.log(this.selected) // RETURNS UNKNOWN
for (j = 0; j < positions[this.selected].SHC.length; j++){
if (positions[this.selected].SHC[j] == this.innerHTML){
positions[this.selected].SHC.splice(j,1);
}
};
;}
tagEl.textContent = tag;
document.getElementById("uldshtags").appendChild(tagEl);
}
},
如何使全局变量也可用于动态创建的函数。
答案 0 :(得分:1)
声明一个变量,并在“ onclick”功能之前分配“ this”,并在“ onclick”内部使用该变量。
<div>
<span class="number">1</span>
<span class="title">ABCD</span>
</div>
<div>
<span class="number">9</span>
<span class="title">AB</span>
</div>
<div>
<span class="number">99</span>
<span class="title">ABC</span>
</div>
<div>
<span class="number">999</span>
<span class="title">A</span>
</div>
<div>
<span class="number">9999</span>
<span class="title">ABCD</span>
</div>