[英]How to get jquery value from for loop in php?
I am trying to alert the text of a div which is in a for loop when it is clicked. 我正在尝试提醒单击div的文本。 There are many divs with same id, i want to get 3 if i click the 3rd or 2 when 2nd is clicked.
有许多具有相同ID的div,如果我单击第3个或单击第2个,则想获得3。 How can i make it with the following code or what must i add to it?
如何使用以下代码或必须添加哪些内容? Thank you.
谢谢。
<? for($i=0; $i<5; $i++) { ?>
<div id="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$("#abc").click(function() {
var thevar= $("#abc").text();
alert (thevar);
}
</script>
You should have unique ids on page. 您应该在页面上具有唯一的ID。 due to this
$("#abc").text()
always returns value for first element in matched selector. 由于这个
$("#abc").text()
总是返回匹配选择器中第一个元素的值。 Rather use abc
as class. 而是使用
abc
作为类。 and to refer element in current context, use $(this)
: 并在当前上下文中引用元素,请使用
$(this)
:
var thevar=$(this).text();
Just try to use a class
instead of using id
inside that loop, 只需尝试使用一个
class
而不是在该循环中使用id
,
<? for($i=0; $i<5; $i++) { ?>
<div class="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text();
alert (thevar);
});
});
</script>
You have syntax error in your code. 您的代码中有语法错误。 Missing
});
缺少
});
. 。 Id should be unique .
ID应该是唯一的。
<? for($i = 0;$i<5;$i++) { ?>
<div class="abc"><? echo $i ?></div> //change
<? } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text(); //change
alert (thevar);
});//was missing
});//was missing
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.