如何用JS替换Dom元素并包含id和JS函数? [英] How to replace Dom element with JS and include an id and a JS function?

查看:138
本文介绍了如何用JS替换Dom元素并包含id和JS函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的跟进:

如何使用Javascript替换DOM元素?

This is a follow up to this question:
How to replace DOM element in place using Javascript?

我不是OP,但我面临着类似的情况。最初的问题是如何使用Javascript替换 span 元素与 span 。给出的答案(谢谢)你 Bjorn Tipling )使用 replaceChild(),使用以下示例:

I wasn't the OP but I am facing a similar situation. The initial question was "how to replace an anchor element with a span using Javascript. The answer that was given (thank you Bjorn Tipling ) was to use replaceChild(), with the following example:

<html>
<head>
</head>
<body>
  <div>
    <a id="myAnchor" href="http://www.stackoverflow">StackOverflow</a>
  </div>
<script type="text/JavaScript">
  var myAnchor = document.getElementById("myAnchor");
  var mySpan = document.createElement("span");
  mySpan.innerHTML = "replaced anchor!";
  myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>

我的跟进是:如何添加/插入ID (例如,xyz)和一个函数(例如, onmouseout ='doWhatever(th is)')到被替换的DOM元素?

My follow up is: how to add / insert an id (e.g., "xyz")and a function (e.g., onmouseout='doWhatever(this)') to the replaced DOM element?

推荐答案

你可以简单地添加一个id属性设置它:

You can add an id property by simply setting it:

mySpan.id = "xyz";

您可以附加如下事件:

mySpan.onmouseout = function() {
    doWhatever(this);
}

我会避免在动态创建DOM元素时设置事件属性。以编程方式分配事件处理程序是正确的方法。

I would avoid setting event attributes when dynamically creating DOM elements. Assigning the event handlers programmatically is the right way to go.

这篇关于如何用JS替换Dom元素并包含id和JS函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆