Simple Javascript Execution

This question already has an answer here:

  • Is there an “exists” function for jQuery? 36 answers

  • 要检查页面中是否存在元素,可以选择它,然后检查length属性(如果使用jQuery)或者它为null(如果使用普通的JS):

    // jQuery
    if ($('.site-header__cart-indicator').length)
      window.setTimeout(redirectCheckout, 2000);
    
    // plain JS
    if (window.querySelector('.site-header__cart-indicator'))
      window.setTimeout(redirectCheckout, 2000); 
    

    Well, for one thing you have a quoting error:

    "<span class="site-header__cart-indicator"></span>"
    

    should be:

    '<span class="site-header__cart-indicator"></span>'
    

    But more to the point , this condition makes no sense. That string would never be in the location (the current URL). It would be on the page.

    Even though your code currently has no jQuery, you do specifically request its use. In which case you can select for that element and see if there are any matches. Something like this:

    if ($('span.site-header__cart-indicator').length > 0)
    
    链接地址: http://www.djcxy.com/p/14692.html

    上一篇: 如何在DOM中检查htmlElement对象

    下一篇: 简单的Javascript执行