当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - if user is on a specific page and a div exisits then do something

问题描述:

This question already has an answer here:

  • How to check if page exists using Javascript

    7 answers

网友答案:

You are just testing that a string exists here (which will always evaluate to true), not that the current URL is equal to what you expect.

if(location.pathname === "/stats" && $(".div").length) {
    // Do Something
}

You need to use the equals parameter to compare against pathname as above.

网友答案:

You could use ajax call and in the success call back you could check if that div element exists

网友答案:

You can use the jQuery.load to load your page and get the content of specific element like the following:

 $( "#result" ).load( "ajax/test.html #container" );

Here, jQuery will load the test.html page and internally will parse and then return the content of element which has id container.

You can see the complete reference in jQuery Load documentation

网友答案:

You will not be able to achieve what you want (unless all pages of interest are in the same domain) without some server-side support of any kind. Browsers will prevent you from gathering content that lives in another domain using AJAX because of the Same-origin Policy.

However the solution is quite simple: implement a server-side service that performs that task and consume it from the client application. If you can't, you may use an online service such as YQL instead of implementing your own.

Please also note that if ('http://www.some-url-in-string.com') doesn't do what you expect. A string doesn't inherit any features based on it's content (1. almost true). I could create a string such as 'the-most-important-string-of-all-times' and it won't be treated differently by the JS engine.

1. Empty strings are falsey while all other strings are truthy.

!!''; //false
!!'anything'; //true
分享给朋友:
您可能感兴趣的文章:
随机阅读: