gpt4 book ai didi

javascript - 将 id 作为参数传递

转载 作者:太空宇宙 更新时间:2023-11-04 08:26:32 25 4
gpt4 key购买 nike

我有一个包含多个div的页面,每个div都有一个来自数据库的ID,在每个div中都有一个like按钮,我想做的是当我点击like按钮传递ID作为我函数中的参数,这是我到目前为止所尝试的:

function addLike
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

<div id="myID" onClick="addLike()">
<button type="button">Like</button>
</div>

最佳答案

ID 必须是唯一的。

无论何时定义内联点击事件处理程序,您都可以考虑传递以下两个变量:

  • this:当前元素
  • event:事件对象

function addLike(ele, e) {
console.log('ID: ' + ele.id);
}
<div id="myID1" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

<div id="myID2" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

<div id="myID3" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

<div id="myID4" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

<div id="myID5" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

<div id="myID6" onclick="addLike(this, event)">
<button type="button">Like</button>
</div>

关于javascript - 将 id 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com