[英]jQuery getting value of attribute inside while loop data coming from AJAX
Let's set up the structure first.让我们先设置结构。
message.php消息.php
<div class="msgcontent content" id="bodycontent">
<div class="getmsglist"></div>
</div>
<script>
setInterval(function(){
$('.getmsglist').load('processes/messagelist.php');
}, 500);
</script>
messagelist.php消息列表.php
<?php while($mat = $stmt->fetch()){ ?>
<div class="messagebox" this-chat="<?php echo $mat['mem_id']; ?>">
// Other Stuffs
</div>
<?php } ?>
So above we can see that in message.php
page the data gets loaded on getmsglist
div from the messagelist.php
page.所以上面我们可以看到,在
message.php
页面中,数据从messagelist.php
页面加载到getmsglist
div 上。 On messagelist.php
the attribute this-chat
contains the user id.在
messagelist.php
上,属性this-chat
包含用户 ID。 I want this user id to be fetched via AJAX.我希望通过 AJAX 获取此用户 ID。 Currently, what I tried returned same user id for all rows.
目前,我尝试为所有行返回相同的用户 ID。 I need to fix that.
我需要解决这个问题。
What I tried...!我尝试了什么...!
$(".msgcontent").click(function() {
var memid = $(".messagebox").attr("this-chat"); // doesn't work (fetches same id for all rows)
//var memid = $(this).children(".messagebox").attr("this-chat"); // this returned undefined as well
var dataString = {
memid: memid
};
console.log(dataString);
});
The $(".messagebox")
doesn't work here and it returns same user id for all rows. $(".messagebox")
在这里不起作用,它为所有行返回相同的用户 ID。 I tried "$(this)" instead but that returned undefined
as it tries to fetch attribute of div ".msgcontent" which does not exist.我尝试了“$(this)”,但它返回了
undefined
,因为它试图获取不存在的 div“.msgcontent”的属性。 How can I fetch this attribute value different for all rows?如何为所有行获取不同的属性值?
Instead of requesting all $('.messagebox')
you should be able to select a single .messagebox
by delegating the click handler with .on() .而不是请求所有
$('.messagebox')
您应该能够通过使用.on()委托单击处理程序来.messagebox
单个 .messagebox 。
$('.msgcontent').on('click', '.messagebox', function() {
var memid = $(this).attr('this-chat');
var dataString = { memid: memid };
console.log(dataString);
});
This way your click handler is bound to the container .msgcontent
but delegated to .messagebox
.这样,您的点击处理程序将绑定到容器
.msgcontent
但委托给.messagebox
。 This way the handler can be bound before there's actual content loaded.这样,可以在加载实际内容之前绑定处理程序。
Now I'm not entirely certain about the custom attribute this-chat
.现在我不完全确定自定义属性
this-chat
。 It's more logical to use data-chat
.使用
data-chat
更合乎逻辑。
var memid = $(this).data('chat');
The data attributes will be converted automatically if you need an integer instead of a string.如果您需要 integer 而不是字符串,则数据属性将自动转换。 But first try to actually get your object in the console log.
但首先尝试在控制台日志中实际获取您的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.