我如何使用javaScript正确生成html标签

how I can generate Properly html tag with javaScript?

本文关键字:html 标签 何使用 javaScript      更新时间:2023-09-26

我创建此代码以替换某些内容并显示一个按钮:

var text = $(item).html().replace(exp, "<button onclick='alert('hi')' id='btnac' href='$1' >Click</button>");

但是在页面中我得到这个,我无法对任何功能显示警报:

<button onclick="alert(" hi')'="" id="btnac" href="www.example.com">Click</button>
var text = $(item).html().replace(exp, "<button onclick='alert('"hi'")' id='btnac' href='$1' >Click</button>");

你有嵌套的单引号,没有转义它们。

之后附加点击处理程序。您还应该将 id 更改为类,因为您可能会在执行此操作时有多个按钮。

var text = $(item).html().replace(exp, "<button class='btnac' href='$1' >Click</button>");
$('.btnac').on( 'click', function() {
  window.alert( "hi!" );
} );