javascript - ReplaceWith 不适用于函数内部

标签 javascript jquery html

我有一个如下所示的a:

<a id="tor" onclick="f1(this);">click to change</a>

现在我想将其替换为另一个标签,例如 p。我尝试了这个但不起作用:

<script type="text/javascript">
    function f1(tor) {
        tor.replaceWith('<p>Hello</p>');//This doesn't work
        alert(tor.id);//But this works
    }                         
</script>

最佳答案

这里的thistor不是一个jQuery对象,而是一个JavaScript HTML元素。将其包裹在 $ 内以启用其上的 jQuery 功能:

function f1(tor) {
   $(tor).replaceWith('<p>Hello</p>');   // This now works.
   alert(tor.id);                        // This is basic JS, so works.
}

片段

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="tor" onclick="f1(this);">click to change</a>
<script type="text/javascript">
  function f1(tor) {
    $(tor).replaceWith('<p>Hello</p>');
    alert(tor.id);
  }
</script>

关于javascript - ReplaceWith 不适用于函数内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100802/

相关文章:

html - float div 内的垂直中心跨度

html - PHP : Inject iframe right after body tag

javascript - JavaScript音频淡出

javascript - 将按钮插入到内容脚本的 DOM 中

javascript - 向我的 js 添加新功能时我的提示不起作用的问题?

javascript - 查找和替换 double “NON BREAKING SPACE” 的正则表达式

javascript - 当鼠标悬停在另一个 div 上时,使用淡入淡出等任何效果更改 div 中的图像

javascript - 使用 Mongodb 和 node.js 在一个页面中处理多个表单

javascript - 如何通过 Angular 指令管理表单有效性?

javascript - 如何使用jquery向div添加类,其中radio具有一定的值