简体   繁体   English

在href属性中使用“ javascript:”更改按钮的值

[英]Use “javascript:” in href attribute to change value of button

Why doesn't this work in a browser? 为什么这在浏览器中不起作用?

<input type="button" id="x">
<a href="javascript:document.getElementById('x').value='something';">Click</a>

Yes, I know that I can use onClick to call a function and put my code there, but is there a way to use 'javascript:' with the href attribute to do simple javascript functions like changing a value? 是的,我知道我可以使用onClick来调用函数并将代码放在此处,但是有没有办法使用带有href属性的'javascript:'来执行简单的javascript函数(例如更改值)?

Assignment "returns" the value assigned. 分配“返回”分配的值。 Returning any kind of value from a javascript: link indicates to the browser that it should replace the document with that value. javascript:链接返回任何类型的值都将指示浏览器使用该值替换文档。

Usually you might see javascript:void(stuff goes here) to suppress the return value. 通常,您可能会看到javascript:void(stuff goes here)来抑制返回值。

You already seem to be aware of why you shouldn't do this, though. 不过,您似乎已经知道为什么不应该这样做。 onClick event handler is a step in the right direction, but really it should be attached externally. onClick事件处理程序是朝着正确方向迈出的一步,但实际上它应该附加在外部。

Yes, that should work and as you know onclick is another easy approach to do it; 是的,这应该有效,并且您知道onclick是另一种简单的方法。

However if you still want to it with href you may try this - (this might look unwillingly big :) 但是,如果您仍然希望使用href,则可以尝试以下操作-(看起来可能不大:)

<input type="button" id="x">
<a href="javascript:(function(){document.getElementById('x').value='something';})();">Click</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM