请帮助jQuery仅执行第一段

时间:2012-12-28 01:48:19

标签: jquery

下面的一些jquery代码工作得很好,就像在段落中添加元素一样。 我的问题是它只显示第一段和重复多少段内的段落。只需查看下面的代码即可。

<!DOCTYPE html>
<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(document).ready(function() {
$('p.content').each(function() {
var content = $(this).html();    
var beforeContent = "<em>";
var afterContent = "</em>";
$(this).html(beforeContent+content+afterContent)
});
})
</script>
<p class="content">Hex value of white is #FFFFFF;</p>
<p class="content">Hex value of black is #000000;</p>
<p class="content">Hex value of blue is #0000FF;</p>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

更改此

var content = $('p#content').html();
$('p#content').html(getX+beforeContent+theRest+afterContent)
<p id="content">Hex value of white is #FFFFFF;</p>
<p id="content">Hex value of black is #000000;</p>
<p id="content">Hex value of blue is #0000FF;</p>

 <p class="content">Hex value of white is #FFFFFF;</p>
<p class="content">Hex value of black is #000000;</p>
<p class="content">Hex value of blue is #0000FF;</p>
var content = $('.content').html();
$('.content').html(getX+beforeContent+theRest+afterContent)

答案 1 :(得分:0)

ID应该是唯一的。您不能在其他元素上使用相同的ID。而是使用class

如果您只需要第一个元素来获取更新,请使用.first()

例如:

$('p#content').first().html(getX+beforeContent+theRest+afterContent)

以下是完整代码,(将id更改为class

<!DOCTYPE html>
<html> 
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(document).ready(function() {
  var content = $('p.content').html();
  var X = /\b\w*x/; 
  var Y = /\b(\w*x)\b(.*)$/; 
  var getX = X.exec(content); 
  var getY = Y.exec(content); 
  var theFirst = getY ? getY[1]:null; 
  var theRest = getY ? getY[2]:null; 
  var beforeContent = "<em>";
  var afterContent = "</em>";
  $('p.content').first().html(getX+beforeContent+theRest+afterContent)
})
</script>
  <p class="content">Hex value of white is #FFFFFF;</p>
  <p class="content">Hex value of black is #000000;</p>
  <p class="content">Hex value of blue is #0000FF;</p>
</body>
</html>​

演示:http://jsfiddle.net/qpBaS/

答案 2 :(得分:0)

如果要完成所有这些操作,您需要遍历p标签

<script type="text/javascript">
    $(document).ready(function() {
        $('p.content').each(function() {
            var content = $(this).html();
            var X = /\b\w*x/; 
            var Y = /\b(\w*x)\b(.*)$/; 
            var getX = X.exec(content); 
            var getY = Y.exec(content); 
            var theFirst = getY ? getY[1]:null; 
            var theRest = getY ? getY[2]:null; 
            var beforeContent = "<em>";
            var afterContent = "</em>";
            $(this).html(getX+beforeContent+theRest+afterContent)
        });
    })
</script>

然后将id更改为class

<p class="content">Hex value of white is #FFFFFF;</p>
<p class="content">Hex value of black is #000000;</p>
<p class="content">Hex value of blue is #0000FF;</p>