I don't know whats the problem of my JavaScript or my code.
I can't get the data-value
of an <a>
tag from HTML.
I don't know what's wrong because I am just a beginner in JavaScript.
I have a loop where I have many categories in my website and I put a value of id from my <a>
tag.
Here is the code:
<div class="list-group">
<?php foreach($data as $single_data) { ?>
<a href="#" id="target" data-value="<?php echo $single_data->Category_id; ?>" class="list-group-item"><?= $single_data->Category_name ?></a>
<?php } ?>
</div>
When i go to show page source it looks good and look like this:
<a href="#" id="target" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" id="target" data-value="2" class="list-group-item">Books</a>
Now here is my JavaScript:
$("#target").click(function() {
var value = $(this).data("value");
alert(value);
});
答案 0 :(得分:1)
标记的ID应该是唯一的
你可以做点什么
<a href="#" id="target1" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" id="target2" data-value="2" class="list-group-item">Books</a>
或者,如果您想捕获两个锚标记的点击事件,则可以使用类选择器
$(".list-group-item").click(function() {
var value = $(this).data("value");
alert(value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="target" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" id="target" data-value="2" class="list-group-item">Books</a>
&#13;
答案 1 :(得分:1)
id
需要独一无二。您可以在问题中使用class作为选择器
$(".list-group-item").click(function() {
var value = $(this).data("value");
alert(value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" data-value="2" class="list-group-item">Books</a>
&#13;
答案 2 :(得分:0)
你需要改变两件事:
和html方面:
$('#myForm input:checkbox').each(function(){
if($(this).is(':checked'))
$(this).attr('disabled', true);
})
JS方面:
<a href="#" id="targetGadget" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" id="targetBook" data-value="2" class="list-group-item">Books</a>
现在,从JS方面来看,不要重复自己,更好的方法是在html端和js中的div中添加$("#targetGadget").click(function() {
var value = $(this).data("value");
alert(value);
});
$("#targetBook").click(function() {
var value = $(this).data("value");
alert(value);
});
元素,为每个元素动态应用<a>
函数div的click()
孩子。
以下是一个例子:
html:
<a>
js:
div id="targets">
<a href="#" id="targetGadget" data-value="1" class="list-group-item">Gadgets</a>
<a href="#" id="targetBook" data-value="2" class="list-group-item">Books</a>
</div>
答案 3 :(得分:-1)
ID始终是唯一的。您不能对不同的DOM元素使用相同的ID。在这种情况下,为他们分配一个类。
将ID更改为类,并相应地在JS代码中进行了更改:
$(".target").click(function() {
var value = $(this).data("value");
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="target list-group-item" data-value="1">Gadgets</a>
<a href="#" class="target list-group-item" data-value="2">Books</a>