jQuery基于其他类更改类元素的值
jquery to change value of a class element based on other class
我有一个页面,其中包含许多相同类型的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);
});
});
相关文章:
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- 如何使用可调整大小的元素重叠其他元素
- JavaScript不显示剩余字符,但适用于其他页面
- jQuery don'当元素被其他元素检索时,它不能正常工作
- 在javaScript中通过DOM获取tagNames而不依赖于其他元素
- 设计模式以实现依赖于其他插件的插件
- jQuery事件在Mozilla上不起作用,并且适用于其他浏览器
- 如果 e.keyCode 是“输入”按钮,并且元素包含其他文本,则验证条件
- jQuery UI 可拖动元素位于其他可拖动元素下
- 在单击时对元素进行动画处理,并在该元素和其他元素上单击鼠标输入/鼠标离开
- 有没有办法知道特定元素存在于其他 html 页面中
- 如何仅触发表单元素与其他代码的部分更改
- 依赖于其他属性的 JavaScript 属性值
- 是否可以将从画布上下文创建的渐变应用于其他画布上下文
- 是否可以使用 Javascript 库测试 SVG 元素?任何其他选项
- 检查文件是否存在于其他服务器上
- 从一个ColModel获取值,执行数学运算并将值应用于其他ColModel
- 已计算的表单数据存在于其他元素中
- youtube's的嵌入式视频不会落后于其他元素
- 如果关键字存在于其他元素中,则禁用或隐藏选择选项