【问题标题】:JQuery add onclick for links with same classJQuery 为具有相同类的链接添加 onclick
【发布时间】:2022-12-13 07:11:33
【问题描述】:

该站点具有与“.tel”类的链接

<a class='tel' href="http://example.com">Link</a>

对于所有这些链接,如何添加

onclick="return gtag_report_conversion('http://example.com/');"

我想得到这样的链接

<a class='tel' onclick="return gtag_report_conversion('http://example.com');" href="http://example.com">Link</a>

【问题讨论】:

  • 任何介绍性的 jQuery 教程或文档都将包含有关如何将点击处理程序附加到一个元素或一组元素的示例。 (而且绝对是不是你在这里说明的是什么。)你尝试了什么,什么没有按预期工作?
  • 还取决于“gtag_report_conversion”的作用 - 如果它是任何类型的 ajax,那么您需要暂停/取消链接。

标签: jquery onclick


【解决方案1】:

如果我答对了你的问题,我认为你正在寻找将自定义属性添加到 HTML 元素的解决方案。如果是这种情况,您可以通过以下方式

 $(document).ready(function () {
    $('a[href].tel').attr('onclick', "return gtag_report_conversion('http://example.com/');");
});
<!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>Document</title>
</head>
<body>
    <div>
        <a class='tel' href="http://example.com">Link - 1</a>
    </div>
    <div>
        <a class='tel' href="http://example.com">Link - 2</a>
    </div>
    <div>
        <a class='tel' href="http://example.com">Link - 3</a>
    </div>
    <div>
        <a class='tel' href="http://example.com">Link - 4</a>
    </div>
    <div>
        <a class='tel' href="http://example.com">Link - 5</a>
    </div>

    <div>
        <a class='telephone' href="http://example.com">Link - 6</a>
    </div>

    <div>
        <a class='telephone' href="http://example.com">Link - 7</a>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多