我有 6 个链接。当我点击任何链接时,我只得到第一个 id 值
var hrefValue = '';
$(".info_link").click(function () {
hrefValue = $(this).attr("id");
console.log('hrefValue : '+hrefValue);
});
最佳答案
要获取链接的 href/id 值,请执行以下操作:
$('#tgg').on('click','.info_link',function(e) {
e.preventDefault();
var hrefValue = this.href;//get the href property of the current clicked element
var id = this.id;//get the id property of the current clicked element
console.log('hrefValue : ' + hrefValue, 'id:' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tgg"><a class="info_link" id="unique_id" href="http://google.com ">google</a></div>
如果您想要一组特定元素的所有 id/href,那么您需要一个全局数组变量,在其中推送被单击元素的 id/href
var id = [];
$(".info_link").click(function() {
id.push(this.id);
console.log('ids : ' + id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="info_link" id="q">0</a>
<a class="info_link" id="q1">1</a>
<a class="info_link" id="q2">2</a>
<a class="info_link" id="q3">3</a>
<a class="info_link" id="q4">4</a>
注意:如果动态附加链接,则需要委托(delegate)单击事件
关于javascript - 点击时获取href值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157635/