【问题标题】:why doesnt my onclick override an earlier executed js function?为什么我的 onclick 没有覆盖之前执行的 js 函数?
【发布时间】:2016-12-22 14:58:21
【问题描述】:

为什么我的 onclick 没有覆盖之前执行的 js 函数?该函数从 php.ini 中的 echo 中触发。该函数被执行并更改图像及其宽度和高度。稍后,如果我单击按钮,我希望图像再次更改,但是只有图像更改,宽度和高度没有更改。

<script>
     function helmfunc() {            
                document.getElementById("helmplace").src = "helmimg/s_helmet.png";  //executes                               
    document.getElementById("helmplace").style.width = "22px"; //executes
    document.getElementById("helmplace").style.height = "31px"; //executes                    
                }
</script>
<img id="helmplace" name="showh" src="redx3.png" width="25" height="30" />
<span onclick="showh.src = x_helm.src; showh.width = x_helm.width; showh.height = x_helm.height; helm.value = 'x helm'">
                <il>
                    <img id="xhelmid" name="x_helm" src="helmimg/x_helmet.png" width="22" height="31" />x Helm
                </il>
            </span> 

在一些 php 中:(在身体最下方)

echo '<script type="text/javascript"> slayerhelmfunc(); </script>';

【问题讨论】:

  • 使用事件监听器而不是 onclick。
  • 是的,现在可以工作了,我被困了这么久有点愚蠢:P
  • @ThomasJuranek 既然它似乎奏效了,您能否将您的评论更改为答案,以便对其进行投票和接受?
  • 我这样做了,正如网站建议的那样,我可能不应该回答 cmets 中的问题。 :P +techturtle

标签: javascript php html


【解决方案1】:

通常接受的在点击时运行代码的方法不是使用 onclick,而是使用事件侦听器。这是一个例子:

<!DOCTYPE html>
<html>
<body>

	<input type="number" id="inputInteger" />
	<input type="submit" id="btnSubmit" text="Submit" />
    
    <p id="result"></p>

	<script type = "text/javascript">
        // Event Listener that Runs "Compute()" on a Click
        document.getElementById("btnSubmit").addEventListener("click", compute);

        // Gets Input Value and Displays it in a <p>
        function compute() {
            var day = document.getElementById("inputInteger").value;
            document.getElementById("result").innerHTML = day;
        }
    </script>
</body>
</html> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多