这适用于 onclick
属性:
<button type="button" onclick="this.style.color='red';">Astringents</button>
这在 onclick 属性中有效,但如果从 head 元素调用则无效:
<head>
<script type="text/javascript">
function red() {
this.style.color='red';
}
</script>
</head>
<button type="button" onclick="red();">Astringents</button>
编辑:我想使用一个函数来为多个按钮提供服务。例如:
<button type="button" onclick="red();">Astringents</button>
<button type="button" onclick="red();">Exfoliators</button>
<button type="button" onclick="red();">Moisturizers</button>
<button type="button" onclick="red();">Masques</button/>
最佳答案
在这种情况下,this
未引用 <button>
元素 - 因此无法编辑元素的属性。
查看关于此主题的 quirksmode 文章 http://www.quirksmode.org/js/this.html
根据文章底部的示例,以下内容应该有效。
<head>
<script type="text/javascript">
function red(obj) {
obj.style.color='red';
}
</script>
</head>
<button type="button" onclick="red(this)">Astringents</button>
关于javascript - JavaScript 的 onclick 属性有效,但如果调用等效函数则无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5012430/