Jquery事件无故触发两次

发布于 2024-08-24 21:38:29 字数 579 浏览 5 评论 0原文

我在使用一个简单的表单时遇到问题,当有人输入内容时我试图触发 ajax 请求。调试后,当事件被触发时,我会收到一个警报,但无论浏览器如何,它都会显示两次。 (忽略输入标签中的“rel”属性,这是为了其他目的,除非您认为是 rel 属性导致了问题)。

<form class="formBig" name="formRegister" id="formRegister" method="post" action="">
    <label class="label" id="locationLabel" for="location">Location</label>
    <input class="input" name="location" id="location" type="text" rel="locationLabel" value="" />
</form>

<script type="text/javascript">
$("#location").click(function() {
    alert($(this).attr('id'));
});
</script>

I'm having a problem with a simple form where i'm attempting to fire an ajax request when someone types something. After debugging I'm left with an alert when the event is fired but it shows up twice, irrespective of the browser. (Ignore the 'rel' attribute in the input tags, that's for something else, unless you think its the rel attribute causing the issue).

<form class="formBig" name="formRegister" id="formRegister" method="post" action="">
    <label class="label" id="locationLabel" for="location">Location</label>
    <input class="input" name="location" id="location" type="text" rel="locationLabel" value="" />
</form>

<script type="text/javascript">
$("#location").click(function() {
    alert($(this).attr('id'));
});
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟织青萝梦 2024-08-31 21:38:29

您将单击事件处理程序绑定到文本输入字段,这意味着它将在您单击时而不是在您键入时调用。尝试使用 keyup 事件。

You are binding a click event handler to a text input field meaning that it will be invoked when you click and not when you type. Try using the keyup event.

兔姬 2024-08-31 21:38:29

我最终弄清楚了,这是因为(出于某种我不知道的原因)我所包含的 jquery 是放在表单之后的。

但是,如果我将其包含在 document.ready 中,则效果很好。我认为这与 DOM 有关。我不知道,当谈到jquery时,我仍然相当n00bish。

并且通过脚本包含从头标签内调用准备好的文档。

I ended up figuring it out, it was because (for some unknown-to-me-reason) the jquery I was including was put in after the form.

However, if I included it within the document.ready, it worked fine. I assume this has something to do with DOM. I dunno, I'm still fairly n00bish when it comes to jquery.

And the document ready is called from within the head-tags via a script include.

终陌 2024-08-31 21:38:29

基本上,它会触发两次,因为有一个与该事件关联的标签,这将导致该事件被触发两次,一次在输入上触发,另一次在关联的标签上触发。

Basically, it triggers twice because there is a label associated with that event which will cause the event to be triggerd twice one on the input and the other on associated label.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文