动态创建元素但使用 <a href>而不是按钮 onClick [英] Dynamically create element but use <a href> instead of a button onClick
本文介绍了动态创建元素但使用 <a href>而不是按钮 onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打算重新使用 W3Schools中描述的 HTML DOM 创建元素方法a> 用于我的表单.
I intend to re-use HTML DOM's create element method described in W3Schools for my form.
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
document.body.appendChild(btn);
}
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
在上面的示例中,button
用于创建 HTML 元素.如何将其更改为使用 href 链接(<a>
标记)而不是按钮的点击事件?
In the example above, a button
is used to create a HTML element. How can I change this to use a href link (an <a>
tag) instead of a button's click event?
推荐答案
将标签更改为锚点,将 href 设置为 "javascript:void(0)" 以防止浏览器执行导航.
Change the tag to anchor, set href to "javascript:void(0)" in order to prevent browser to perform navigation.
<!DOCTYPE html>
<html>
<body>
<p>Click the link to make a BUTTON element with text.</p>
<a href="javascript:void(0)" onclick= "myFunction()" > Try it</a>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
document.body.appendChild(btn);
}
</script>
</body>
</html>
这篇关于动态创建元素但使用 <a href>而不是按钮 onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文