2011-08-26 156 views

回答

17

您将需要使用JavaScript才能检查元素是否存在并执行重定向。

假设div有一个id(如DIV ID = “elementId”),你可以简单地做:

if (!document.getElementById("elementId")) { 
    window.location.href = "redirectpage.html"; 
} 

如果您正在使用jQuery,下面将是解决办法:

if ($("#elementId").length === 0){ 
    window.location.href = "redirectpage.html"; 
} 

增加:

如果您需要检查特定单词的div的内容(因为我认为这是你现在问的)你可以做这个(jQuery):

$("div").each(function() { 
    if ($(this).text().indexOf("copyright") >= 0)) { 
     window.location.href = "redirectpage.html"; 
    } 
});​ 
+0

你可以简单地使用'location'而不是'window.location'; – arnaud576875

+1

是的,你可以:)但是你可以在同一个作用域内有一个局部变量“location”,它将覆盖全局位置变量。这就是为什么我倾向于使用“窗口”。字首。 –

4

使用jQuery,您可以检查它像这样:

如果($( “#divToCheck”)){// 存在DIV} 其他{// OOPS的div失踪 }

if ($("#divToCheck").length > 0){ 
    // div exists 
} else { 
    // OOPS div missing 
} 

if ($("#divToCheck")[0]) { 
    // div exists 
} else { 
    // OOPS div missing 
} 
+0

第一个代码不会总是评估为真? – arnaud576875

+0

@ arnaud576875:感谢您对它进行标记。更新了答案。 –

2

什么不同于页面上其他人的这个特殊的div?

如果它有一个ID,你可以这样通过document.getElementById:

var div = document.getElementById('the-id-of-the-div'); 
if (!div) { 
    location = '/the-ohter-page.html'; 
} 

您还可以检查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'; 
} 
+0

(注意编者:location **是** window.location) – arnaud576875

1

您可以使用jQuery为

if ($("#mydiv").length > 0){ 
    // do something here 
} 

在这里阅读更多:http://jquery.com/

编辑:修复了下面评论中指出的错误。对不起,在忙碌的一天工作,并得到太高兴触发。

+1

'$(“#mydiv”)'总是返回一个对象并且总是评估为真 – arnaud576875

+0

非常感谢您的回复,但您知道如何检查div的内容,例如,如果div包含单词[版权],它会将访问者重定向到另一个页面。谢谢 – shandoosheri

相关问题