我有一个带有动态ID的子元素的上录制按钮。我如何获取该子元素的ID?
我正在尝试将投票功能添加到博客网站上,每个博客都有一个唯一的ID,我需要在数据库中记录投票,并在HTML中更新投票。<<<<<<<<<<<<
$(".plus").click(function() {
var myvar = $(".plus").find("h4");
console.log(myvar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='plus'>
<h4>up</h4>
<h3 id='{{blog.id}}'>0</h3>
</button>
提供了您要获取H3元素的ID并将其打印在Myvar检查此链接
$(".plus").click(function(){
var myvar = $( ".plus" ).find( "h3" ).attr("id");
console.log(myvar);
});
jQuery .children()
将是最好的选择: -
$(".plus").click(function(){
var myvar = $( ".plus" ).children( "h3" ).attr('id');
console.log(myvar);
var myvar1 = $( ".plus" ).children( "h4" ).attr('id');
console.log(myvar1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='plus'>
<h4 id="h4_id">up</h4>
<h3 id='h3_id'>0</h3>
</button>
为什么.children()
在您的情况下最好是
: - https://stackoverflow.com/a/648014/4248328
,尽管您可以使用它来获取子元素的ID:
$(".plus").click(function() {
var myvar = $(this).find("h3")[0].id;
console.log(myvar);
});
但是,我觉得,如果您将标记更改一些,也可以使用一些data-*
属性:
$('.plus').click(function(){
// jquery version
var blogId = $(this).data('blogId');
console.log("jq .data() version::::", blogId);
// js version
var blgId = this.dataset.blogId;
console.log("js .dataset version::::", blgId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='plus' data-blog-id='{{blog.id}}'>
<h4>up</h4>
<h3 id='{{blog.id}}'>0</h3>
</button>
您可以这样使用。
$(".plus").click(function() {
var myvar = $(this).find("h3").attr("id");
alert(myvar);
});
如果您有多个 .plus
项目,并且想要在单击时获取每个项目的id
,则可以使用this
上下文。
$(".plus").click(function() {
var myvar = $(this).find("h4").text();
var myid = $(this).find("h3").attr("id");
console.log(myvar, myid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='plus'>
<h4>up</h4>
<h3 id='id_1'>0</h3>
</button>
<button class='plus'>
<h4>down</h4>
<h3 id='id_2'>0</h3>
</button>
使用此代码,当您单击.plus
按钮时,它将查找<h4>
摘要的值和<h3>
的ID。
在单击功能中使用$(".plus")
选择器而不是this
,当您单击一个时,将选择页面中的所有按钮,并且attr()
方法将仅返回第一个ID而不是当前一个ID。