一次设置多个子元素的值?

J. *_*Doe 1 javascript jquery

例如我有这个:

<div class="person">
    <div class="firstname"></div>
    <div class="lastname"></div>
    <div class="age"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法用jQuery一次设置所有子元素的值?也许是这样的:

$('.person').xxx('.firstname', function(){
    $(this).text('John');
}).xxx('.lastname', function(){
    $(this).text('Smith');
}).xxx('.age', function(){
    $(this).text('12');
});
Run Code Online (Sandbox Code Playgroud)

还是其他任何方式?

谢谢!

I a*_*ica 7

如果你已经嫁给了链接一切的想法,正如你的代码似乎建议的那样,请查看...jQuery.prototype.end()

$(".person") // root selector
  .find(".firstname").text("john")
  .end() // back to person
  .find(".lastname").text("doe")
  .end()  // back to person
  .find(".age").text("18");
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="person">
    <div class="firstname"></div>
    <div class="lastname"></div>
    <div class="age"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

这不会假设子节点相对于彼此的位置.

或者,如果您确定所有这些项共享同一个父项,则可以使用:jQuery.prototype.siblings()

$(".person")
  .find(".firstname").text("john")
  .siblings(".lastname").text("doe")
  .siblings(".age").text("18");
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="person">
  <div class="firstname"></div>
  <div class="lastname"></div>
  <div class="age"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

说实话,你没有明确地定位这些项目.如果有的话,效率会降低.


Eri*_*ips 5

非常接近,存储人员,并找到相关元素并设置它们.

var $person = $('.person');
$person.find('.firstname').text('John');
$person.find('.lastname').text('Smith');
$person.find('.age').text('12');
Run Code Online (Sandbox Code Playgroud)

或者自己写:

$.fn.with = function(elems,selector,action){ 
return this.each(function(){
    $(elems).find(selector).each( function(i,e) {
      action(e)});
});
Run Code Online (Sandbox Code Playgroud)

然后你可以:

$('.person')
  .with('.firstname', function(e) { e.text('john'); })
  .with('.lastname', function(e) { e.text('Smith'); })
  .with('.age', function(e) { e.text('12'); })
Run Code Online (Sandbox Code Playgroud)

我最近没有写过jquery扩展,所以它可能会以一种几乎完全按照你编写它的方式进行改进.