jQuery调用实际存在的null元素 [英] jquery calling null element that actually exists

查看:85
本文介绍了jQuery调用实际存在的null元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码可以在localhost上运行,但是当我在自己的站点上实现它时,它就不能运行. 错误日志说它正在请求一个不存在的元素.我已经得出结论,因为该元素是动态加载的,所以它看不到该元素.

My code works on localhost, but when I implement it on my site, it doesnt. The error log says it's calling for an element that doesn't exist. I've reach to the conclusion that it can't see the element because the element is loaded dynamically.

该元素是类.newsitem_text,它是一个包含博客文章的div.我相信在页面加载该类之前,jQuery正在调用该类.

The element is the class .newsitem_text, it's a div that contains a blog post. I believe that the jquery is calling for the class before the class is being loaded by the page.

这里是一个小提琴例子: http://jsfiddle.net/ku6L240c

Here is one example fiddle: http://jsfiddle.net/ku6L240c

错误: Uncaught TypeError: Cannot read property 'html' of null 47-ganhe-dinheiro-atraves-de-downloads:1093 Uncaught SyntaxError: Unexpected token ILLEGAL

The error: Uncaught TypeError: Cannot read property 'html' of null 47-ganhe-dinheiro-atraves-de-downloads:1093 Uncaught SyntaxError: Unexpected token ILLEGAL

代码:

<javascript>
            var wordList = $(".newsitem_text").html().split(' ');
            var newHtml = '';

            $.each(wordList, function(index, word){
              newHtml += ' ' + word;
              if (index == 50) {
                newHtml += '<div>Some HTML</div>'     
              }        
            })
            ;

            $(".newsitem_text").html(newHtml);


</javascript>

如何让脚本等待页面加载类,然后执行脚本?

How can I make the script wait until the class is loaded by the page, then it gets executed or something?

推荐答案

似乎您在JS代码中执行动态HTML,并立即尝试获取刚刚添加的标签.如果是这种情况,您的代码将必须等待并继续检查,直到浏览器呈现新HTML并将节点添加到DOM,然后您才能查询它们或执行某些操作.

Seems you are doing dynamic HTML within JS code and immediately trying to get the just added tags. If that is the case, your code will have to wait and keep checking until browser rendered your new HTML and add the nodes to DOM, then you can query them or do something about.

我发现可行的唯一方法是使用usint setTimeOut并继续检查然后执行您的最后一条语句.我在下面创建一个函数,该函数检查等待并检查某些条件,然后执行回调函数.

The only way I found works is usint setTimeOut and keep checking then execute your last statement. I create a function below that checks wait and check for certain condition then execute a call back function.

//A function to wait until either times up, or until a pass in "funct" returns "true", which ever occured first.
//funct - callback function, to be returned true or false.
//done - an optional callback function for notify when waiting is over.
//timeout - the amount of time in million-second to wait.
//caller - optional string of caller for monitoring if multiple waiting session.
function waitToSync(funct, done, timeout, caller) {
  //This is  a hack synchronize to wait until funct() returns true or timeout becomes < 0.
  caller = caller || '';
  if ((funct === undefined) || typeof (funct) != 'function') return;
  function waiting() {
    if (!funct()) {
      var dt = new Date();
      console.log(caller + " waiting: " + dt.format('yyyy-mm-dd h:MM:ss'));
      if ((timeout - 1000) > 0)
        setTimeout(waiting, 1000); //1 second.
      else {

        console.log(caller + ': waitToSync timed out!!!');
        document.body.style.cursor = 'default';
      }
      timeout -= 1000;
    }
    else {
      if (done !== undefined && (typeof done === 'function'))
        done();
    }
  }
  waiting();
}

动感十足或想等待的事情.然后调用WaitToSync

Do all you dynamic or anything to want to wait. Then call the WaitToSync

 $.each(wordList, function(index, word){
     newHtml += ' ' + word;
     if (index == 50) {
        newHtml += '<div>Some HTML</div>'     
     }        
  });

  waitToSync(
     function wait() { return document.getElementsByClassName("newsitem_text").length > 0; }, 
     function dosomething() { $(".newsitem_text").html(newHtml); },
     10000, //wait up to 10 seconds.
     'dynamic add HTML');

这篇关于jQuery调用实际存在的null元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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