1

下面的一些 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>
4

3 回答 3

0

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

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

例如:

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

这是完整的代码,(更改idclass

<!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/

于 2012-12-28T01:56:38.127 回答
0

如果你想做所有这些,你需要遍历 p-tags

<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>

然后更改idclass

<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>
于 2012-12-28T01:58:31.667 回答
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)
于 2012-12-28T01:54:53.203 回答