【问题标题】:This Keyword Usage in element And Parameter元素和参数中的 this 关键字用法
【发布时间】:2017-01-19 09:58:30
【问题描述】:

我正在学习 JavaScript 事件,我的观点是“this”关键字用于对象或全局对象,但在此代码中,此关键字用于函数回调参数中的元素中,为什么?

Q1)我们如何在代码中的元素onClick事件中使用'this'?

Q2)其次,有时我将此关键字放在函数参数参数中,因此错误生成'Unexpected Token'。

请帮忙解答这两个问题。

HTML 代码:

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">

<div class="d1" onclick="highlight(this)">1 
    <div class="d2" onclick="highlight(this)">2
        <div class="d3" onclick="highlight(this)">3
        </div>
    </div>
</div>

<script>
function highlight(elem) {
    elem.style.backgroundColor='yellow'
    alert(elem.className)
    elem.style.backgroundColor = ''
}
</script>

</body>
</html>

【问题讨论】:

标签: javascript this keyword


【解决方案1】:

Q1) 我们如何在这段代码的元素 onClick 事件中使用“this”? A)HTML中的'this'指的是接收事件的HTML元素。在你的情况下,元素是'div'

Q2)其次,有时我将此关键字放在函数参数参数中,因此错误会生成“意外令牌”。 A)我看到'this'是一个隐式参数,当我们调用基于对象的函数时,它将自动传递,函数调用附加到。所以我觉得,b/w函数参数的'this'和隐含的'this'会有冲突

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2021-10-12
    相关资源
    最近更新 更多