gpt4 book ai didi

javascript - 如何通过jquery添加动态属性?

转载 作者:行者123 更新时间:2023-12-03 04:47:58 25 4
gpt4 key购买 nike

我需要添加分析来跟踪每个按钮的点击次数以进行标注。

我的代码如下...

var headers = $(".callouts .callout-inner h2").text();
var buttons = $(".callouts .callout-inner a.button");
buttons.addClass("button-data");
buttons.attr("data-button-info", headers);
a.button {
text-decoration: none;
padding: 10px;
background: #00007f;
color: #fff;
border-radius: 10px;
font-family: Arial;
text-transform: uppercase;
font-size: 12px;
font-weight: bold;
transition: all 0.5s ease;
}

a.button:hover {
background: #efefef;
color: #00007f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container callouts">
<div class="col-sm-6 col-md-4 callout-wrapper">
<div class="callout">
<img class="img-responsive" alt=" " src="#" width="350" height="117">
<div class="callout-inner">
<h2>First Header 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sed lacus placerat, malesuada magna vitae, blandit risus. Nunc lobortis justo eu purus vestibulum porta.</p>
<a class="button" href="#" target="_self">Button 1</a>
</div>
<div class="callout-bottom"></div>
</div>
</div>
<div class="col-sm-6 col-md-4 callout-wrapper">
<div class="callout">
<img class="img-responsive" alt=" " src="#" width="350" height="117">
<div class="callout-inner">
<h2>Second Header 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sed lacus placerat, malesuada magna vitae, blandit risus. Nunc lobortis justo eu purus vestibulum porta.</p>
<a class="button" href="#" target="_self">Button 2</a>
</div>
<div class="callout-bottom"></div>
</div>
</div>
<div class="col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-0 callout-wrapper callout3">
<div class="callout">
<img class="img-responsive" alt=" " width="350" height="117">
<div class="callout-inner">
<h2>Third Header 3</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sed lacus placerat, malesuada magna vitae, blandit risus. Nunc lobortis justo eu purus vestibulum porta.</p>
<a class="button" href="#" target="_self">Button 3</a>
</div>
<div class="callout-bottom"></div>
</div>
</div>
</div>

我得到的最终结果是每个按钮的 data-button-info 属性包含每个 h2 (如果您在运行代码片段后检查按钮,您可以更好地看到发生了什么)。我的目标是让每个按钮都有相应的 h2 文本值作为其用于跟踪目的的属性。例如,“Button 1”包含一个“data-button-info”属性,其值为“First Header 1”。我不明白为什么它用所有 h2 值填充属性。

非常感谢这里的任何帮助和指导,因为我对 jquery/js 非常陌生。

提前致谢!

最佳答案

此代码可以满足您的需求

$(".callouts .callout-inner").each(function(){
var header = $(this).find("h2").text();
var button = $(this).find("a.button");
button.addClass("button-data");
button.attr("data-button-info", header);
});

关于javascript - 如何通过jquery添加动态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42789058/

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