简体   繁体   English

在 JavaScript 中指定的按钮的 onclick 属性在 html 检查中不可见

[英]onclick attribute of button specified in JavaScript doesn't visible in html inspect

i have made a code where made a button named "Clear Cart" and passes it to the html code via javascript.我制作了一个代码,其中制作了一个名为“清除购物车”的按钮,并通过 javascript 将其传递给 html 代码。 I added the attribute 'onclick' on that button but when I inspect that button on page then button appears without 'onclick' attribute.我在该按钮上添加了“onclick”属性,但是当我检查页面上的该按钮时,按钮会出现没有“onclick”属性。 All other attributes are appearing okay but 'onclick' attribute is not visible there.所有其他属性都显示正常,但“onclick”属性在那里不可见。 this is my code:这是我的代码:

popStr = popStr + "<button id ='clearcart' class='btn btn-primary' onclick='clearCart()'> Clear Cart </button>";
document.getElementById('popcart').setAttribute('data-content', popStr);

This is the output I am receiving这是我收到的输出

<button id="clearcart" class="btn btn-primary"> Clear Cart </button>```

您用来注入新元素的库似乎对您的 html 进行了“清理”(删除了 onclick)。

Your question is not clear about how it is added to the DOM from data-content attribute.您的问题不清楚它是如何从data-content属性添加到 DOM 的。 There should not be any problem if you are setting this HTML from data attribute to DOM with Element.innerHTML如果您使用Element.innerHTML将此 HTML 从 data 属性设置为 DOM,则应该没有任何问题

Following is the sample code based on the assumptions:以下是基于假设的示例代码:

let popStr = "";

popStr = popStr + "<button id ='clearcart' class='btn btn-primary' onclick='clearCart()'> Clear Cart </button>";

document.getElementById('popcart').setAttribute('data-content', popStr);

function addToDom() {
   document.querySelector("#output").innerHTML = document.getElementById('popcart').dataset.content;
}

function clearCart() {
  alert("working!")
}

Workign example: https://jsbin.com/tavoyozewa/edit?html,js,output工作示例: https ://jsbin.com/tavoyozewa/edit ? html,js,output

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

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