我想提醒所有p元素的文本(基本jquery)

时间:2011-09-14 16:47:05

标签: javascript jquery html

我正在学习JQuery。我看来是一个新的Jquery学生。

这是我的html页面:

<html>
<head>
    <title>Jquery 1</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $("document").ready(function(){
        var num = 0;
        $("p").each(function(){
            var data = data + $(this:eq(num)).html();
            num =+1;
            });
        alert(data);
        });
    </script>
</head>
<body>
    <p>
        Deneme
    </p>
    <p>
        Deneme2
    </p>
</body>
</html>

我想提醒所有p元素的文字。这段代码不起作用.. 我该怎么办?

6 个答案:

答案 0 :(得分:5)

存在多个小问题:

  • 首先,在回调函数之外声明data变量,否则变量只在函数本身内部可见。
  • $(this:eq(num))替换为$(this)。在jQuery.each的回调中,this是当前元素。
  • 您不需要num变量

    $("document").ready(function(){
        var data = ''; // data will be visible from inside of the inner function:
        $("p").each(function(){
            data += $(this).html(); // `this` is the current element
        });
        alert(data);
    });
    

在此处尝试:http://jsfiddle.net/DBme5/

答案 1 :(得分:5)

将代码更改为:

$("document").ready(function(){
    var data = "";
    $("p").each(function(index, element) {   // note that the .each() handler has two parameters that can be used also
        data += $(this).html();              // "this" inside the .each() handler function is the current DOM element in the iteration
    });
    alert(data);
});

.each()处理函数内部,this值是迭代中的当前DOM元素。此外,.each()处理程序上还有两个参数,也可以使用。 index是您在迭代中的位置(从0到length-1),element是当前DOM元素(与this相同的值)。

您可以详细了解.each() here

答案 2 :(得分:3)

<script type="text/javascript">
    $(function(){
        var data = "";
        $("p").each(function(){
            data += $(this).text();
        });
        alert(data);
    });
</script>

答案 3 :(得分:2)

可能不只是这个?

$("p").each(function(){
   alert($(this).text()); 
});

答案 4 :(得分:1)

您的代码存在一些错误

$(this:eq(num)).html(); // $(this) already refers to the current element,
                        // so $(this).html() is enough

num =+1; // should be: num += 1

这是一个正确的版本

var data = '';

$( 'p' ).each( function () {

    data += $( this ).html();

});

这是一个使用纯JavaScript的解决方案

var data = '',
    elements = document.getElementsByTagName( 'p' );

for ( var x = 0, len = elements.length; x < len; x += 1 )
{
    data += elements[x].innerHTML;
}

答案 5 :(得分:1)

如果您有(或想要)文字内容,则根本不需要.each()

alert( $('p').text() );

jQuery会为你连接它。

DEMO: http://jsfiddle.net/8apPN/


如果您要显示嵌套的HTML标记,请改为执行此操作:

var html = $.map( $('p'), function(v) { return v.innerHTML; }).join('');

alert( html );

DEMO: http://jsfiddle.net/8apPN/1/