检查div是否存在,如果不存在则重定向

Sha*_*ara 12 html javascript

如何检查div我的页面上是否存在某些内容,如果不存在,则将访问者重定向到另一个页面?

Lee*_*ley 24

您需要使用JavaScript来检查元素是否存在并执行重定向.

假设div有一个id(例如div id ="elementId"),你可以简单地做:

if (!document.getElementById("elementId")) {
    window.location.href = "redirectpage.html";
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是jQuery,以下是解决方案:

if ($("#elementId").length === 0){
    window.location.href = "redirectpage.html";
}
Run Code Online (Sandbox Code Playgroud)

加成:

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

$("div").each(function() {
    if ($(this).text().indexOf("copyright") >= 0)) {
        window.location.href = "redirectpage.html";
    }
});?
Run Code Online (Sandbox Code Playgroud)


Har*_*Joy 5

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

if ($("#divToCheck")){ // div 存在 } else { // OOPS div 丢失 }

或者

if ($("#divToCheck").length > 0){
  // div exists
} else {
  // OOPS div missing
}
Run Code Online (Sandbox Code Playgroud)

或者

if ($("#divToCheck")[0]) {
  // div exists
} else {
  // OOPS div missing
}
Run Code Online (Sandbox Code Playgroud)