jQuery基于其他类更改类元素的值

jquery to change value of a class element based on other class

本文关键字:元素 于其他 其他 jQuery      更新时间:2023-09-26

我有一个页面,其中包含许多相同类型的div,如下所示。

<div class="post_right" data-icon = "arrow-r">
 <p>Posted at:</p>
 <div class="post_time"> 
  <%= post.created_at.strftime("%I:%M %P") %> 
 </div>
 <div class="post_timer"></div>
</div>

我有一个jquery脚本,它将从"post_time"类读取并通过向其添加值来更新post_timer类。

$("document").ready(function() {
    $(".post_timer").each(function(){
    var post_time = $(".post_time").html()
    $(this).html(post_time);
    });     
});

但是所有"post_timer"类值都会通过第一个post_time值进行更新。无论如何,我都可以在整个页面中根据相应的"post_time"类值更新post_timer值。

您需要获取同一索引的$(".post_time"); 否则.html只会得到第一个(如您所见)。

var post_time = $(".post_time").eq($(this).index()).html();

http://jsfiddle.net/kVNGN/

只需将 DOM 遍历到适当的元素即可。由于在您的示例中,.post_time 元素似乎是 .post_timer 元素的前一个同级元素,因此您可以使用.prev [docs]

$(".post_timer").html(function() {
    return $(this).prev().html();
    // or more structure independent: 
    // return $(this).siblings('.post_time').html();
}); 

jQuery有更多的遍历方法。

$("document").ready(function() {
    $(".post_timer").each(function(){
    var post_time = $(this).prev(".post_time").html();
    $(this).html(post_time);
    });     
});