1

I'm trying to use jQuery to change paragraph text based upon the class of the div in which it resides.

I want each of the class names in the array to replace the p text within their respective divs. Right now I just get the last div's class name for the p text.

<div class="ph player">PHILIPPINES<p class="topic">Test topic</p></div>
<div class="sl player">SOLOMON ISLANDS<p class="topic">Test topic</p></div>
<div class="fi player">FIJI<p class="topic">Test topic</p></div>
<div class="sm player">SAMOA<p class="topic">Test topic</p></div>

<script>
var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
   $(".topic").text(this);
});
</script>

Thanks for looking. Total beginner here.

4

4 回答 4

3

我想你想要的是:

$.each(divArr,function(i,val) {
  $('.'+val+' p.topic').text(val);
});

这将使每个 div 的段落文本等于两个字母的类名

于 2012-06-23T00:35:00.673 回答
1

您必须找到合适的.topicnot all .topics:

var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
   $('.' + value).find(".topic").text(this);
});
于 2012-06-23T00:32:29.027 回答
1

确保您只选择要更改的 div:

var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
   $("div." + value + " .topic").text(value);
});
于 2012-06-23T00:32:37.733 回答
0
$.each(divArr, function (i,e) { 
    $("."+this).find("p.topic").text(this);
});

关键是正确使用选择器。

" this" 取值 "ph", "sl"...

因此"."+this将识别 JQuery/CSS 语法中的类(.ph、.sl ...)

$("."+this)因此选择正确div的 ,我们将在其中用类细化p标签.topic并替换文本(再次,this)。

于 2012-06-23T00:33:22.603 回答