Jquery。已经无法正常处理部分项目

时间:2013-03-01 18:00:54

标签: javascript jquery dom

这是我的功能:

  $().ready(function() {
    console.log('DOM is ready');
    var songtoload = $(".soundcloudid").first().html();
    console.log(songtoload)
    if (songtoload == undefined) {
      console.log('Hide the widget');
      $("#sc-widget").hide();
    }
    if (songtoload !== undefined) {
      console.log('Show the widget');
      $("#sc-widget").show();
    }
  });

出于某种原因,即使我在Chrome控制台中收到以下回复,歌曲仍然会以“未定义”的形式出现:

$(".soundcloudid").first().html();
"31204641"

我是否错误地使用.ready?

修改 这样做的目的是仅在播放列表部分

中存在歌曲时显示SC播放器小部件

2 个答案:

答案 0 :(得分:1)

由于songcloudid对象是动态加载的...切换小部件的检查应该移动到动态加载这些对象的函数。:

function refreshPlaylist() {
    // ... some code to refresh it
    $.ajax({
        // your ajax call to refresh it
        success: function (data) {
            // ... load your data first and put it on the page
            var $songToLoad = $('.soundcloudid:first');
            if ($songToLoad.length == 1) {
                console.log($songToLoad.html())
                console.log('Show the widget');
                $("#sc-widget").show();
            }
            else {
                console.log('Hide the widget');
                $("#sc-widget").hide();
            }
        }
    });

}

答案 1 :(得分:0)

$().ready将等到$()的结果准备就绪。 $()是一个空集。我认为您想要的是$(document).ready(function() {...})或其快捷方式:$(function() {...})

相关问题