0

div 内的示例文本:

I am at the first line.
I am at the second line.
I am at the third line.
I am at the end of the first paragraph.

问题:我想制作一个脚本,它将使:

  1. 所有“第一”都将被涂成蓝色
  2. 所有“第二个”都将被涂成绿色
  3. 所有“第三个”都将被涂成红色和粗体

请在此处查看非工作代码..

添加了代码链接

4

3 回答 3

2

Here you go

$(function(){   
  $('#text').attr('value','first').css('color','#0000FF');
  $('#text').attr('value','second').css('color','#00FF00');
  $('#text').attr('value','third').css('color','#FF0000');
  $('#text').attr('value','third').css('font-weight','bold');
});
于 2013-12-20T05:21:51.297 回答
0

这几乎是不可能实现的,如果适用于一篇文章或段落,它将不适用于另一篇文章或段落。在我看来,唯一的解决方案是包含一个 html 标记,它将定义这些标记,然后为它们应用 jquery 代码,

<p class='paragraph'>
<span class='firstline'>This is the first line.</span>
<span class='secoundline'> This is the second line. </span>
<span class='thirdline'> This is the third line.</span>
<span class='endparagraph'>This is the end of the first paragraph.</span>
</p>

现在在 jquery 部分你可以做类似的事情

$(function(){
  $('.firstline').css({'color':'blue' , 'font-weight':'bold'});
  .....

})
于 2013-01-24T03:03:04.980 回答
0

您可以使用 jQuery:nth-child选择器来执行此操作。您可以使用 css() 或通过向段落添加类并使用 CSS 设置样式(这将是理想的)来应用样式。

I've created a JSFiddle with the two versions: http://jsfiddle.net/RJ8sC/5/. You just need to change the wrapper div ID to yours and you should be good to go.

Here's the jQuery code for quick reference:

$(document).ready( function() {
    $('#example p:nth-child(1)').css('color','blue');
    $('#example p:nth-child(2)').css('color','green');
    $('#example p:nth-child(3)').css({color:'red', 'font-weight': 'bold'});
});

// ALTERNATIVE USING CLASSES - THIS IS BETTER PRACTICE

$(document).ready( function() {
    $('#example2 p:nth-child(1)').addClass('first');
    $('#example2 p:nth-child(2)').addClass('second');
    $('#example2 p:nth-child(3)').addClass('third');
});
于 2013-01-24T03:41:36.937 回答