Javascript 将焦点放在不使用ID的输入字段上

Javascript 将焦点放在不使用ID的输入字段上,javascript,jquery,html,Javascript,Jquery,Html,当选择特定单选按钮时,我试图突出显示表单中的输入字段。虽然我已经做到了这一点,但我不明白为什么我的特定解决方案会起作用 以下是HTML: <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>

当选择特定单选按钮时,我试图突出显示表单中的输入字段。虽然我已经做到了这一点,但我不明白为什么我的特定解决方案会起作用

以下是HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
    <meta charset="UTF-8">
    <script type="text/javascript" src="script.js"></script>
    <title>Testing jQuery on Forms</title>
</head>
<body>
    <div id="form">
    <h3>The form</h3>
        <form name="main_form">
            <fieldset style="width: 300px;">
                <legend>General Information</legend>
                <p>Do you have a name?</p>
                <input style="float: left" name="name_or" id="name_or_yes" type="radio" value="yes">
                <legend for="name_or_yes">Yes</legend>
                <input style="float: left" name="name_or" id="name_or_no" type="radio" value="no" checked="checked">
                <legend for="name_or_no">No</legend>
                <br/>
                Name: <input type="text" name="name" id="#name_field">
            </fieldset>
        </form>
        <button id="submit_form">Submit</button>
    </div>
    <div id="results"></div>
</body>
</html>

在表单上测试jQuery
形式
一般资料
你有名字吗

对 不
姓名: 提交
以下是JS:

$(document).ready(function() {
    $('#name_or_yes').click(function() {
        $('input[name=name]').focus();
    });

    $('#submit_form').click(function() {
        var toAdd = $("input[name=name]").val();
        $('#results').append("<p>"+toAdd+"</p>");

    });
});
$(文档).ready(函数(){
$('#name_或_yes')。单击(函数(){
$('input[name=name]')。focus();
});
$(“#提交表单”)。单击(函数(){
var toAdd=$(“输入[name=name]”).val();
$(“#结果”)。追加(“”+toAdd+”

”; }); });
我不明白为什么focus()在我使用名称输入字段的id(#name_field')时对其不起作用。它只在我使用输入[name=name]方法时起作用。这让人倍感困惑,因为以下几点非常有效:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
    $("#txtfocus").focus();
});
</script>
</head>

 <body>
     <input type="text" id="txtfocus2"><br/>
     This text box is set focused: <input type="text" id="txtfocus">
 </body>

</html>

$(文档).ready(函数(){
$(“#txtfocus”).focus();
});

此文本框设置为聚焦:

任何帮助或建议都将不胜感激

在这里查看
id

<input type="text" name="name" id="#name_field">

试着这样做:

<input type="text" name="name" id="name_field">


是id选择器,但不应出现在HTML中。

输入的
id应为
“名称字段”
,而不是
“名称字段”


谢谢你们两位

这些都是当你花太多时间看同一段代码时会发生的错误

我想投票给你,但我没有足够的声誉点数(

<input type="text" name="name" id="name_field">