请帮助jQuery仅针对第一段执行 [英] Please help jQuery execute only for the first paragraph

查看:83
本文介绍了请帮助jQuery仅针对第一段执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的某些jquery代码可以正常工作,就像在段落中添加元素一样. 我的问题是,它仅显示第一段,并重复显示正文中段数的次数.只需在下面查看我的代码即可.

Some jquery code below works fine just like adding element inside the paragraph. My problem is it's only displaying the first paragraph and repeated number of times of how many number of paragraph in the body. Just check my code below.

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

推荐答案

如果要对所有p标签进行遍历,则需要遍历p标签.

You need to loop through the p-tags if you want to do all of them

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

这篇关于请帮助jQuery仅针对第一段执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆