var that = this
2017-08-30 15:50
148 查看
为什么说一般情况下,我们对于this,更喜欢先用一个变量定义,如 var that = this.
原因如下:
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button>点击</button>
</body>
<script>
window.onload = function(){
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function(){
var li = document.getElementsByTagName('li');
for(var i=0;i<li.length;i++){
if(li[i].innerHTML==2){
btn.innerHTML="测试";
}
}
}
}
</script> 举个简单的例子,如上述代码所示如果我这个代码量再多一点的话,我可以直接在btn.onclick下一行写上var that = this,这样在判断语句里面的代码就可以直接写成that.innerHTML="测试".
用var that = this主要是为了代码量很多的时候能够在子元素里面方便的调用上级元素。
原因如下:
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button>点击</button>
</body>
<script>
window.onload = function(){
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function(){
var li = document.getElementsByTagName('li');
for(var i=0;i<li.length;i++){
if(li[i].innerHTML==2){
btn.innerHTML="测试";
}
}
}
}
</script> 举个简单的例子,如上述代码所示如果我这个代码量再多一点的话,我可以直接在btn.onclick下一行写上var that = this,这样在判断语句里面的代码就可以直接写成that.innerHTML="测试".
用var that = this主要是为了代码量很多的时候能够在子元素里面方便的调用上级元素。
相关文章推荐
- 小程序var that=this
- javascript中var that=this
- What does var that = this; mean in javascript?
- javascript中var that=this
- javascript中var that=this;是什么意思
- JavaScript 中的 var that = this
- js常见的var that = this的用法
- 为什么在js中要写var this =that?
- javascript中var that=this
- 【JavaScript】var that = this
- 为什么要写var that = this;
- 微信小程序 this和that详解及简单实例
- “(null)” is of a model that is not supported by this version of Xcode. Please use a different device
- Incorrect decrement of the reference count of an object that is not owned at this point by the caller1
- Consider this problem again and again, resolve that AndEngine not run in AVD Finally
- Search a 2D Matrix IIWrite an efficient algorithm that searches for a value in an m x n matrix. This
- Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
- Multilib version problems found. This often means that the root...
- Error This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. T
- System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt".