检查类和id是否存在,然后更改h1,然后在时间限制后重定向页面

check if class and id exist then change h1 then redirect page after time limit

本文关键字:然后 时间 重定向 id 是否 存在 检查 h1      更新时间:2023-09-26

我在HTML5页面中启动JS/JQ时遇到了一些问题。基本上,我想检查是否存在以下ID和以下类:

ID:page_blog

CLASS:页面当前

<section class="page current" id="page_blog" style="z-index: 99; left: -50px;">
...
...
...

如果它们存在,则在2-3秒后重定向,将H1更改为

正在加载。。。

<h1><button data-target="home" data-target-activation="click" class="back backwards"></button>Loading...</h1>

这就是我目前所拥有的:

<script type="text/JavaScript">
        $(document).ready(function () {
            $('li#blogLink.tile').click(function (e) {
                e.preventDefault(); //will stop the link href to call the blog page
                setTimeout(function () {
                    alert("this has worked");
                    //window.location.href = "http://www.site.co.uk/blog/"; //will redirect to your blog page (an ex: blog.html)
                }, 2000); //will call the function after 2 secs.
            });
        });
</script>

我的页面上现在有以下内容:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("jquery", "1.7");
    </script>

<script type="text/JavaScript">
    $(document).ready(function () {
            if ($(".page.current").length) { // section exists
                $("h1").text("Loading...");
                setTimeout(function () {
                    window.location.href = "http://www.website.co.uk/blog/";
                }, 2000);
        });
</script>

但是检查类/id是否存在并没有启动?

试试这个:

$('li#blogLink.tile').click(function (e) {
    e.preventDefault();
    if ($("#page_blog.page.current").length) { // section exists
        $("h1").text("Loading...");
        setTimeout(function() {
            window.location.href = "http://www.site.co.uk/blog/";
        }, 2000);
    }   
});

小提琴示例

此外,值得一提的是,您的选择器过于挑剔。应该只有一个id为#page_blog#blogLink的唯一元素,因此在它们的选择器上包含标记和类是多余的代码。

相关文章: