Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript与'冲突;这';参考_Javascript_Jquery - Fatal编程技术网

Javascript与'冲突;这';参考

Javascript与'冲突;这';参考,javascript,jquery,Javascript,Jquery,我有一段javascript代码(使用jQuery)说: $('.duration').each(function() { $(this).html(this.duration_text); }); 它迭代类“duration”的每个元素,并根据需要设置文本。问题是,它设置的文本来自成员变量,因此使用this.duration\u文本。“this”引用正在被jQuery在迭代中使用的“this”引用破坏 我怎样才能避免这次碰撞 虽然答案的基本概念可能与标记为重复的问题完全相同,但我并不

我有一段javascript代码(使用jQuery)说:

$('.duration').each(function() {
    $(this).html(this.duration_text);
});
它迭代类“duration”的每个元素,并根据需要设置文本。问题是,它设置的文本来自成员变量,因此使用this.duration\u文本。“this”引用正在被jQuery在迭代中使用的“this”引用破坏

我怎样才能避免这次碰撞


虽然答案的基本概念可能与标记为重复的问题完全相同,但我并不清楚这是同一个问题。事后看来,这是肯定的,但在搜索我自己时,我没有找到它,也不清楚如果我找到了它,这是同一个问题。

在创建循环之前,您可以创建对此的引用,然后使用
self
引用具有属性的对象
duration\u text

var self = this;
$('.duration').each(function() {
    $(this).html(self.duration_text);
});
尽管你可以做到:

$('.duration').html(this.duration_text);

在创建循环之前,您可以创建对
的引用,然后使用
self
引用具有属性
duration\u text
的对象:

var self = this;
$('.duration').each(function() {
    $(this).html(self.duration_text);
});
尽管你可以做到:

$('.duration').html(this.duration_text);

可以使用闭包变量保存对外部对象的引用

var self = this;
$('.duration').each(function() {
  $(this).html(self.duration_text);
});
但是在给定的代码段中,由于您将相同的内容分配给所有
duration
元素,因此可以使用

$('.duration').html(this.duration_text);

可以使用闭包变量保存对外部对象的引用

var self = this;
$('.duration').each(function() {
  $(this).html(self.duration_text);
});
但是在给定的代码段中,由于您将相同的内容分配给所有
duration
元素,因此可以使用

$('.duration').html(this.duration_text);

简洁明了。谢谢。简单明了。谢谢