[英]Copy one attribute to another in the same child element of a set of children in JQuery
Wow, so that's a mouthful. 哇,好吃 I've been struggling with this as I'm still a newbie with JQuery selectors.
我一直在为此苦苦挣扎,因为我仍然是使用JQuery选择器的新手。 Any help with this will be greatly appreciated.
任何帮助,将不胜感激。 I have a situation where I'm selecting a sub-set of child div (class='B') from a parent div (id='A') using
.children()
and .slice()
. 我有一个情况我选择使用子集从父DIV(ID = 'A')子DIV(类= 'B')的
.children()
和.slice()
Furthermore, I need to copy the value of longdesc
attribute of each grandchild div (class='C') to its div content. 此外,我需要将每个孙子div (class ='C')的
longdesc
属性值复制到其div内容。 I was thinking of something like below, but I don't know how to reference the correct grandchild div when trying to obtain the value of the longdesc
. 我在想类似下面的内容,但是在尝试获取
longdesc
的值时,我不知道如何引用正确的孙子div。 Maybe there's a better approach to this? 也许有更好的方法吗? HELP!
救命!
HTML: HTML:
<div id="A">
<div class="B">
<div class="C" longdesc="value1"></div>
</div>
<div class="B">
<div class="C" longdesc="value2"></div>
</div>
<div class="B">
<div class="C" longdesc="value3"></div>
</div>
<div class="B">
<div class="C" longdesc="value4"></div>
</div>
</div>
JQuery: JQuery的:
$start = 0;
$end = 2;
$('#A').children().slice($start, $end).find('.C').html("??value of longdesc??");
Output: 输出:
<div id="A">
<div class="B">
<div class="C" longdesc="value1">value1</div>
</div>
<div class="B">
<div class="C" longdesc="value2">value2</div>
</div>
<div class="B">
<div class="C" longdesc="value3">value3</div>
</div>
<div class="B">
<div class="C" longdesc="4"></div>
</div>
</div>
Many thanks in advance! 提前谢谢了!
Use the version of .html()
that take a function as parameter .. 使用以函数 .. 为参数的
.html()
版本 。
$('#A').children().slice($start, $end+1).find('.C').html(function(){
return $(this).attr('longdesc');
});
Demo at http://jsfiddle.net/aaFt9/1/ 演示在http://jsfiddle.net/aaFt9/1/
You also need to use $end + 1
to match the value3
because slice
second argument is up-to but not including it ( see Array.prototype.slice()
docs at MDN ) 您还需要使用
$end + 1
来匹配value3
因为slice
第二个参数是最新参数,但不包括它( 请参见MDN的Array.prototype.slice()
文档 )
Additionally if that is your real html structure, you can skip the .children()
and find the .C
elements directly.. 此外,如果这是您真正的html结构,则可以跳过
.children()
并直接查找.C
元素。
$('#A').find('.C').slice($start, $end+1).html(function(){
return $(this).attr('longdesc');
});
Demo at http://jsfiddle.net/aaFt9/2/ 演示位于http://jsfiddle.net/aaFt9/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.