3

我想知道如何更改 div 的 html 内容。

这是起点:

<div id="container">
    <div class="fruits">apple</div>
    <div class="fruits">banana</div>
    <div class="fruits">strawberry</div>
</div>

页面输出:

苹果
香蕉
草莓

输出应更改为:

猫狗
鱼...或
类似
的东西。

我想我必须用 .each() 或其他东西迭代“水果”类。我知道如何更改单个 div 的单个元素或内容,但我不明白当您多次使用同一个类时它是如何工作的。

类=“水果”
类=“水果”
类=“水果”
……

希望你能帮忙。

4

3 回答 3

7
var animals = ["cat", "dog", "fish"];

$(".fruits").text(function(i){
  return animals[i];
});

将您的动物存储到一个数组中,在选择器上使用回调
循环,并通过返回与当前索引匹配的索引来修改文本()。.text().fruitsanimalsianimals[i]

如果您有比数组长度更多的选择器元素,您可以使用以下方法对结果取模:return animals[i%animals.length];

jsBin 演示


由于不清楚您将 Animals 字符串存储在哪里,
您也可以使用这个简单的示例来实现您所需要的并且使用data-*属性:

<div class="fruits" data-to="cat">apple</div>
<div class="fruits" data-to="dog">banana</div>

jQuery:

$(".fruits").text(function(i){
  return $(this).data().to;     // or use: // this.dataset.to;
});

jsBin 演示

于 2015-01-23T00:43:30.653 回答
3

Roko在 jQuery 中提供了一个答案,但不碍事。

没有必要使用 jQuery 来完成这样一个简单的任务,这里是一个纯 JavaScript。(小提琴

var pets = [ "cat", "dog","fish" ];
var fruits = document.querySelectorAll(".fruits"); // Partial support in IE8
for( var i = 0 ; i < fruits.length ; i ++ )
    fruits[i].innerHTML = pets[i];

这是@Roko提供的更快的版本。

var pets = [ "cat", "dog", "fish" ],
    fruits = document.getElementsByClassName("fruits"), // Not supported in IE8
    tot = fruits.length,
    i = 0;
for(;i<tot;) fruits[i].innerHTML = pets[i++];

基准 jQuery vs JavaScript vs Roko 的 JavaScript

希望能帮助到你!

于 2015-01-23T00:47:43.083 回答
1

使用 .each 看起来像这样。我已将其设置为使用数组来回切换以保存另一个集合。但是,Roko C. Buljan 的答案通过避免一些不必要的方法调用,以更少的努力完成了基本相同的事情,所以我肯定会说他是更好的答案。

var otherVals = ['dog', 'cat', 'fish'];

function go() {
  $('.fruits').each(function(index) {
    var temp = $(this).html();
    $(this).html(otherVals[index]);
    otherVals[index] = temp;
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="fruits">apple</div>
  <div class="fruits">banana</div>
  <div class="fruits">strawberry</div>
</div>
<input type="button" value="go" onclick="go()" />

于 2015-01-23T00:50:27.113 回答