2

我有一个按钮,单击它会将文本的颜色更改为红色。

下面是一些基本的JS:

function colorChange() {
 document.getElementById('text').style.color = "red";
}

和 HTML:

<p id="text">some text</p>
<button type="button" onclick="colorChange()">red</button>

不适用于 JSfiddle 或 Codepen。但是 - 当我制作一个相同的本地 HTML 文件时,它会按预期工作。

为什么这个 vanilla Javascript 在 Codepen/JSfiddle 中不起作用的原因是什么?不涉及任何库(jQuery、React 等)。我的第一个直接想法是在 JSFiddle 中,您可以在负载类型的设置中设置一个属性。我将其设置为onLoad但仍然无法正常工作。Codepen 看起来并不提供对此的控制。

JSFiddle: https ://jsfiddle.net/mo5pro4a/1/

代码笔: https ://codepen.io/anon/pen/YVYZXj

更新:Codepen 实际上看起来还不错 - 现在主要是 jsfiddle 的问题。

4

4 回答 4

1

因为你在html中使用了onclick attr,但是在这个标签之后插入了js。

<script>如果您在 html 区域中添加它会正常工作。

<script>
function colorChange() {
    document.getElementById('text').style.color = "red";
}
</script>
<p id="text">some text</p>
<button type="button" onclick="colorChange()">red</button>

谢谢伊姆西曼。另一种方法是单击 JavaScript 齿轮并将加载类型更改为小提琴中的“头部”或“身体”。

于 2017-05-08T19:59:21.387 回答
1

这是因为加载 JavaScript 的时间。如果您将小提琴中的负载类型更改为No wrap - in <head>(请参阅此示例),它将起作用。

它也适用于 StackOverflow 上的一个片段:

function colorChange() {
 document.getElementById('text').style.color = "red";
}
<p id="text">some text</p>
<button type="button" onclick="colorChange();">red</button>

为避免此问题,请务必<script>在运行任何 JavaScript 或指定任何代码(例如onclick属性)之前添加您的标签。

于 2017-05-08T20:03:48.440 回答
1

发生这种情况是因为在onclickis 之前读取了script并且当时colorChange无法找到该函数。

这也是不使用内联 HTML 事件属性的另一个原因(请参阅此处了解更多其他属性)。更改代码以遵循标准并将 JavaScript 与 HTML 分开。

将所有这些代码放在window加载 DOM 内容后运行的事件处理程序中,例如:

// When the document has been fully parsed...
window.addEventListener("DOMContentLoaded", function(){

    // Register the event handler via the DOM standard:
    document.querySelector("button").addEventListener("click", colorChange);

    function colorChange() {
    	document.getElementById('text').style.color = "red";
    }

});
    <p id="text">some text</p>
    <button type="button">red</button>

或者,将此代码放入紧挨在结束标记 ( )<script>之前的元素中,或<body></body>

<body>
<p id="text">some text</p>
<button type="button">red</button>

<script>
// Register the event handler via the DOM standard:
document.querySelector("button").addEventListener("click", colorChange);

function colorChange() {
	document.getElementById('text').style.color = "red";
}
</script>
</body>

无论哪种方式,都不应使用内联 HTML 事件属性。

于 2017-05-08T20:04:07.110 回答
0

那是因为你需要在定义html之前定义脚本或者只是把你想要运行的js代码放在onClick()方法里面。

选项 1:https ://jsfiddle.net/mo5pro4a/5/ 选项 2:https ://jsfiddle.net/mo5pro4a/9/

于 2017-05-08T20:03:07.497 回答