繁体   English   中英

如何通过onclick在innerhtml中传递事件

[英]how to pass event in innerhtml by onclick

我正在制作一个关于添加到购物车的项目。 我想通过来自innerhtml的onclick传递事件。
这是我的 html 代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add to cart</title>
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
  crossorigin="anonymous"
/>
</head>
<body>
 <div id="cards-container" class="row align-items-center my-3 p-3"></div>
 <script src="./script.js"></script>
</body>
</html>

这是我的js代码

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = document.getElementById('cards-container');
 cardsContainer.innerHTML='';
 data.map(element => {
    const cardDiv = document.createElement('div')
    cardDiv.className= "col-md-4"
    cardDiv.innerHTML=`
    <div class='card p-5 m-1'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" id='card-button' onclick='setLocalStorage(e)'>Add to Card</button>
    </div>
    `
    cardsContainer.appendChild(cardDiv);
});
}

function setLocalStorage(e){
 console.log("clicked",e)
}

我在控制台https://d.pr/i/JCjI77 中收到此错误

我之前也遇到过几次这个问题。

首先,我建议无论如何使用 jquery。 在编写纯 html 时,我几乎总是使用 jquery。 它使与 DOM 的交互更加容易。 所以这里是 id="card-button" 元素的 onClick 事件的 jquery 示例。 普通的点击事件在 jquery 中不起作用。 您必须在文档上设置它,然后进一步设置一个选择器:

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = $('#cards-container');
 cardsContainer.html("");
 data.map(element => {
    cardsContainer.append(`
    <div class='card p-5 m-1 col-md-4'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" id='card-button'>Add to Card</button>
    </div>
    `
});
}

$(document).on("click", "#card-button", function(e) {
    setLocalStorage(e)

    // or you can just place the contents of setLocalStorage directly 
    // into here! 
})

function setLocalStorage(e){
 console.log("clicked",e)
}

您可以在此处从按钮元素中删除 onClick。 确保你记得导入 jquery。 理想情况下是缩小版。

但你还有另一个更重要的问题

您正在创建多个具有相同 ID(卡片按钮)的添加卡片按钮。 您需要将卡片按钮设置为一个类。 这样它可以应用于多个元素。 我建议向与用户 ID、索引或任何其他唯一标识符关联的按钮或 cardDiv 添加一个 ID。 通过这种方式,您可以识别实际按下的是哪个用户或卡片按钮,并采取相应措施。 这是带有类而不是 ID 的更新后的 jQuery

fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))

function show(data){
 const cardsContainer = $('#cards-container');
 cardsContainer.html("");
 data.map(element => {
    cardsContainer.append(`
    <div class='card p-5 m-1 col-md-4'>
        <h3>${element.name}</h3>
        <h5>${element.email}</h3>
        <button class="btn btn-primary" class="card-button" id='some-unique-id'>Add to Card</button>
    </div>
    `
});
}

$(document).on("click", ".card-button", function(e) {
    setLocalStorage(e)

    // or you can just place the contents of setLocalStorage directly into here! 

    // Here you can grab the jquery object with $(this), or use the 
    // ID with e.target.id with the e.target.id, etc...
    clickedButton = $(this);
    clickedButtonID = e.target.id;
})

function setLocalStorage(e){
 console.log("clicked",e)
}

我不经常使用没有 jQuery 的纯 HTML,所以我不能肯定地回答你是否想走那条路。 好像这个以前的线程回答了这个问题,绝对比我能做的更好。

无法在尚未附加到文档的 HTML 元素上使用 getElementById

祝你好运!!

暂无
暂无

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

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