繁体   English   中英

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

[英]I want to alert all p elements' text (basic jquery)

我正在学习JQuery。 正如我所见,我是一名新的Jquery Student。

这是我的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元素的文本。 该代码不起作用..我该怎么办?

有多个小问题:

  • 首先,在回调函数之外声明data变量,否则该变量仅在函数本身内部可见。
  • $(this:eq(num))代替$(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/

将代码更改为此:

$("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()更多信息。

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

可能不只是这个吗?

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

您的代码中有一些错误

$(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;
}

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

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

jQuery将为您串联它。

演示: http : //jsfiddle.net/8apPN/


如果要显示嵌套的HTML标记,请执行以下操作:

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

alert( html );

演示: http : //jsfiddle.net/8apPN/1/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM