无法使用 jQuery 按 id 选择按钮

Cannot select button by id with jQuery

本文关键字:id 选择 按钮 jQuery      更新时间:2023-09-26

我很困惑:

$(document).ready(function() {
    var sendButton = $('#send');
    var name = $('#name');
}

在我的 JavaScript 文件中。当我在Chrome中打开控制台时,sendButton没有附加到任何东西,而是name附加到name元素。

HTML 包含:

<input id="name"><input id="send" type="button" value="send">

这是奇怪的部分:如果我在控制台中输入:

> $('#send')
[<input id=​"send" type=​"button" value=​"send">]

所以看起来选择器是有效的,但它在 JS 文件中不起作用,而仅适用于按钮。有什么想法吗?

编辑:对不起,我在这里给出片段,我有准备好文档的东西。

使用 document.ready 。它可能会有所帮助

$( document ).ready(function() {
// now your initialization
});

期望您正在搜索元素,直到页面呈现。用户 $(document).ready() 事件

在 dom ready 后加载它们:

$(function() {
  var sendButton = $('#send');
  var name = $('#name');
});