jQuery ajax 调用在 php 中,而循环只返回第一个 id



我正在开发每隔几秒钟更新一次股票价格的wordpress插件。我在html表格中显示股票价格,该表格在php循环中执行,该表格将股票作为wordpress帖子抓取。在我的代码中,我需要帖子的标题来调用获取特定股票价格的函数。

<?php  $query = new WP_Query( $args );
if ($query->have_posts()) :
$i = 1;
while ($query->have_posts()) : $query->the_post();
?>
<td class="name"><?php the_title(); ?></td>
<td class="price" id="<?php echo $i; ?>" value="<?php echo get_the_title(); ?>"></td>

我想将特定股票帖子的 id 传递给 jQuery ajax 函数。

jQuery(document).ready( function($){
setInterval(callMe, 5000);
});
function callMe(){
var id = $('.price').attr("id");
var titleInput = jQuery('#' + id).attr("value");
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
dataType: 'json',
data: {
action: 'myaction',
post_title: titleInput
},
success: function(response){
$('#' + id).html(response);
}
});
}

这只返回第一个 id,然后也只传递第一个帖子标题,而不是其他标题。

问题只在于我如何调用 id?我正在玩我如何调用 var id,但无法让它工作。

var id = $('.price').attr("id");

如果您对如何解决此问题有一些建议,请提供帮助。

$('.price')返回一个集合,虽然有一些函数(如.css()(直接对它们进行操作,但.attr()只对单个元素进行操作,因此它只返回第一个元素的值:

console.log($('.price').length)
console.log($('.price').attr('id'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price" id="id1" value="value1"></div>
<div class="price" id="id2" value="value2"></div>

您必须为每个单独的元素调用函数:

function callMe() {
$('.price').each(function() {
var id = $(this).attr("id");
var titleInput = $(this).attr("value");
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
dataType: 'json',
data: {
action: 'myaction',
post_title: titleInput
},
success: function(response) {
$('#' + id).html(response);
}
});
});
}

最新更新