javascript - 将 id 作为参数传递

标签 javascript jquery html css

我有一个包含多个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/

相关文章:

javascript - 为什么原始查询更新时未定义 Sequelize 元数据?

javascript-将结果集从数据库推送到数组失败

javascript - done() 回调的意义何在?

javascript - 排除选择菜单形式的onclick onclick事件

javascript - JQuery 后回调不起作用

javascript - 100% 宽度容器内的中心 div,左右浮动宽度

php - 使用 PHP 和 HTML 的评论框仅返返回告表单的最后评论信息

javascript - 主从 kendo ui 网格(当主网格中的选择行获取详细信息网格中的条目时)

jquery - 如图所示动态排列div

javascript - 当从 javascript 调用字符串时,Latex 不渲染?