javascript - 为什么我的 onclick 不覆盖之前执行的 js 函数?

标签 javascript php html

为什么我的 onclick 没有覆盖之前执行的 js 函数?该函数从 php 中的 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。这是一个例子:

<!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> 

关于javascript - 为什么我的 onclick 不覆盖之前执行的 js 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285971/

相关文章:

javascript - 如何使图像部分滚动,然后保持固定,然后在通过某个部分时滚动?

JavaScript 不会改变背景图像

javascript - 如何访问 JSON 对象中的值?

javascript - 未捕获的ReferenceError : app is not defined in controller,模块和路由

php - MVC : should Model return error message or error code

html - CSS - 无法使 CSS 类正常工作,但内联样式确实有效

jquery - 如何在 imageMap 的精确坐标处插入一个 div

html - chrome 不支持应用程序/rtf 类型

php - 从文件夹加载图像列表

php - 哪个是比较两个 url 的最好和最快的方法?