Javascript 检查 div 是否存在,如果不存在则重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7204155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether a div exists and redirect if not
提问by Shady Nawara
How do I check whether a certain div
exist on my page and if not, redirect the visitor to another page?
如何检查div
我的页面上是否存在某个页面,如果不存在,将访问者重定向到另一个页面?
回答by Lee Crossley
You will need to use JavaScript to be able to check if the element exists and do the redirect.
您将需要使用 JavaScript 来检查元素是否存在并进行重定向。
Assuming the div has an id (e.g. div id="elementId") you can simply do:
假设 div 有一个 id(例如 div id="elementId"),您可以简单地执行以下操作:
if (!document.getElementById("elementId")) {
window.location.href = "redirectpage.html";
}
If you are using jQuery, the following would be the solution:
如果您使用的是 jQuery,则解决方案如下:
if ($("#elementId").length === 0){
window.location.href = "redirectpage.html";
}
Addition:
添加:
If you need to check the content of divs for a specific word (as I think that is what you are now asking) you can do this (jQuery):
如果您需要检查特定单词的 div 内容(因为我认为这就是您现在要问的),您可以这样做(jQuery):
$("div").each(function() {
if ($(this).text().indexOf("copyright") >= 0)) {
window.location.href = "redirectpage.html";
}
});?
回答by Harry Joy
Using jQuery you can check it like this:
使用 jQuery,您可以像这样检查它:
if ($("#divToCheck")){
// div exists
} else {
// OOPS div missing
}
if ($("#divToCheck")){ // div 存在 } else { // OOPS div 丢失 }
or
或者
if ($("#divToCheck").length > 0){
// div exists
} else {
// OOPS div missing
}
or
或者
if ($("#divToCheck")[0]) {
// div exists
} else {
// OOPS div missing
}
回答by Arnaud Le Blanc
What differenciate this particular div from others on the page ?
这个特定的 div 与页面上的其他 div 有何不同?
If it has an ID, you can to this with document.getElementById:
如果它有一个 ID,你可以使用 document.getElementById 来实现:
var div = document.getElementById('the-id-of-the-div');
if (!div) {
location = '/the-ohter-page.html';
}
You can also check the content of the div:
您还可以检查 div 的内容:
var div = document.getElementById('the-id-of-the-div');
var html = div.innerHTML;
// check that div contains the word "something"
if (!/something/.test(html)) {
location = '/the-ohter-page.html';
}
回答by havardhu
You can use jQuery for that
你可以使用 jQuery
if ($("#mydiv").length > 0){
// do something here
}
Read more here: http://jquery.com/
在此处阅读更多信息:http: //jquery.com/
Edit: Fixed the error pointed out in the comment below. Sorry, busy day at work and got too trigger happy.
编辑:修复了下面评论中指出的错误。抱歉,忙了一天的工作,太高兴了。