【问题标题】:not redirecting to other page using jQuery [duplicate]不使用 jQuery 重定向到其他页面 [重复]
【发布时间】:2021-12-30 00:09:33
【问题描述】:

我对 jQuery 和 html 还很陌生,浏览了 google 和这些论坛都无济于事。

这是我的 HTML 代码

<html>
<head>
    <link rel="stylesheet" href="reset.css" type="text/css">
    <link rel="stylesheet" href="index.css" type="text/css">
    <script src="./jquery.js" type="text/javascript"></script>
</head>
<body>
    <div id="container">
        <form id="form">
            <h1>Koks yra leistingas greitis miesto ribose?</h1>
            <input type="radio", id="ats1", name="atsakymas", value="1" ></input>
            <label for="ats1"> a</label>
            <br>
            <input type="radio", id="ats2", name="atsakymas", value="2" ></input>
            <label for="ats2"> b</label>
            <br>
            <input type="radio", id="ats3", name="atsakymas", value="3" ></input>
            <label for="ats3"> c</label>
            <br>
            <button id="Rinktis" type="submit">Rinktis</button>
            <button id="close">Išeiti</button>
        </form>
    </div>
    <script src="./index.js" type="text/javascript"></script>
</body>

这是我认为应该将我重定向到另一个页面的 jQuery 行

    $("#Rinktis").click(function (){
        document.location.href = "http://google.com";
        return;
    })

但它什么也没做,我做错了吗?

【问题讨论】:

  • 使用window.location.href 而不是document
  • @Zak 在现代浏览器中,document.location 已经映射到 window.location(尽管后者更可取)。
  • 使用browser console (dev tools)(点击F12)并阅读任何错误。开发工具提供了一个 Network 选项卡。查找这两个脚本资源。看看单击按钮时会发生什么。请确认:资源是否找到(例如 HTTP 200 响应)?如果不是,则请求哪个实际 URL?相应地修改 URL。尝试https 而不是http。如果你得到 ReferenceError: $ is not defined.”,请确保 jquery.js 确实存在并且包含 jQuery。下面的答案有用吗?删除所有关闭的&lt;/input&gt; 标签;这些都是多余的。
  • @Zak 无论是文档还是窗口,它都不起作用。 Sebastian Simon 是的,我已经通过控制台进行了检查,没有错误或警告,jQuery.js 脚本加载正常
  • $("#form").submit(function(event){ event.preventDefault(); window.location.href = "http://google.com"; });

标签: javascript html jquery


【解决方案1】:

您的代码(在 JS 中)应该是:

$("#Rinktis").click(function (e) {
    e.preventDefault();
    window.location.href = "http://www.google.com";
})

return 声明是不必要的。 click 函数中的 e 参数代表 Event 对象。由于您要覆盖表单的提交操作(不知道为什么),您需要第一行来停止默认操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-01
    • 2012-03-16
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多