[英]How to add data to the anchor tag in HTML and access it using jQuery?
以下是我的锚标记的HTML代码:
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed">Fixed</a>
现在我想在上面的锚标记中添加一个问题id,并在用户点击这个超链接时在jQuery中访问它。 对于它我尝试下面的代码,但它没有为我工作。
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21627&que_issue_status=0" title="Fixed" href="#fixedPopContent" class="fixed" data="21627">Fixed</a>
它的jQuery代码如下:
$(document).ready(function() {
$(".fixed").click(function(e) {
var t2 = $(this).data();
alert(t2);
});
});
它在警告框中给我消息[对象对象] 。 任何人都可以帮助我将值设置为锚标记并在jQuery中访问它?
尝试这样的事情
HTML
<a href="#fixedPopContent" class="fixed" data-q_id="21627"></a>
JavaScript的
$(document).ready(function() {
$(".fixed").click(function(e) {
var t2 = $(this).data('q_id');
alert(t2);
});
});
您可以在html元素上添加属性data-sample_name
。 在jquery中使用
$('your_element_id').data('sample_name');// to get value
$('your_element_id').data('sample_name','new value');// to set value
我假设你正在尝试做这样的事情:
$(document).ready(function() {
// you can change the selector, `"key"` and its value below
$("a.fixed").data("key", 21627); // on document ready, store the necessary data
// ^-- Insert a dynamic value here if required
$(".fixed").click(function(e) {
alert($(this).data("key")); // 21627
});
});
.data()
存储一个键值对。 所以在这里,我创建了一个名为'key'
并将其存储为值21627
并在点击时提醒对应于密钥'key'
。
你有一个[object Object]
因为.data()
将数据存储在一个对象中,并且通过传递零参数,你基本上将与.fixed
相关的对象存储到t2
。
一个更简单的方法是:
<a id="your-data" onclick="callfunction(this.id)">Fixed</a>
callfucntion(id)
。 function callfucntion(id) { var data = id; // if more than one data, you can se split() }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.