【问题标题】:Error javascript only get first value data-href?错误 javascript 只能获取第一个值 data-href?
【发布时间】:2013-08-15 04:15:26
【问题描述】:

我有一个示例代码:

<div id="fb-root"></div>
<div class="fb-comments" id="fb-comment" data-href="http://fb.com/t1" data-num-posts="3" data-width="590" ></div> 

<div class="fb-comments" id="fb-comment" data-href="http://fb.com/t2" data-num-posts="3" data-width="590" ></div> 

还有 javascript:

<script>
window.fbAsyncInit = function() {
    FB.init({
        appId : 'xxx', // App ID
        channelUrl : 'xxx', // Channel File
        status : true, // check login status
        cookie : true, // enable cookies to allow the server to access the session
        xfbml : true // parse XFBML
    });

    FB.Event.subscribe('comment.create', function(response) {
        var href = jQuery('.fb-comments').attr('data-href');
        alert(href);
    });
}
</script>

错误 jquery 只得到第一个值是http://fb.com/t1,没有得到http://fb.com/t2

【问题讨论】:

  • 使用jQuery.each 循环遍历元素

标签: javascript jquery facebook facebook-comments


【解决方案1】:
var thestring = '';

$('.fb-comments').each(function () {
    thestring += $(this).attr('data-href') + ' ';
});

【讨论】:

    【解决方案2】:

    DEMO

    使用.each() 遍历类fb-comments 的每个元素

    var href='';
    jQuery('.fb-comments').each(function () {
        href += $(this).attr('data-href') + ' ';
    })
    

    DEMO

    或使用.map()

    href 是数组的形式,使用下面的代码

    var href= jQuery('.fb-comments').map(function(){
        return jQuery(this).attr('data-href');
    });
    console.log(href);
    

    【讨论】:

    • 使用.map() 不运行,返回值[object Object]
    • .map() crates 数组以便访问数组我们href[index] 例如。 href[0]href[1] 用于访问数组值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多