简体   繁体   English

为什么不能读入输入值并显示警报?

[英]Why can't I read in my input value and display the alert?

I've looked this up and tried it out but it isn't working. 我已经查过并尝试了,但是没有用。 If the user submits a in the input field, then it should alert it works but for some reason it isn't working. 如果用户在输入字段中提交a ,则应该提醒it works但是由于某种原因它不能正常工作。

What am I doing wrong and how can I fix it? 我在做什么错,我该如何解决?

 $(function() { var $list, $newItemForm; $list = $('ul'); $newItemForm = $("newItemForm"); $newItemForm.on('submit', function(e) { e.preventDefault(); // var text = $('input:text').val(); var text = $('itemField').val(); console.log(text); $list.append('<li>' + text + '</li>'); // $('input:text').val(''); if (text == "a") { alert("it works"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="newItemForm"> <input type="text" id="itemField" placeholder="item" /> <input type="submit" id="add" value="add" /> </form> 

You forgot to prefix # in the selector while referencing the form ( $("newItemForm") ) and input value ( $('itemField').val() ) in variables: 您在引用表单( $("newItemForm") )和输入值( $('itemField').val() )时忘记在选择器中添加前缀#

 $(function() { var $list, $newItemForm; $list = $('ul'); $newItemForm = $("#newItemForm"); $newItemForm.on('submit', function (e) { e.preventDefault(); // var text = $('input:text').val(); var text = $('#itemField').val(); console.log(text); $list.append('<li>' + text + '</li>'); // $('input:text').val(''); if(text == "a") { alert("it works"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="newItemForm"> <input type="text" id="itemField" placeholder="item"/> <input type="submit" id="add" value="add"/> </form> 

I think the problem is with the selectors for "newItemForm" and "itemField". 我认为问题出在“ newItemForm”和“ itemField”的选择器上。

In jQuery, when you want to select elements by ID you need to prepend the # character. 在jQuery中,当您想通过ID选择元素时,您需要在#字符前添加。

The code should be as follows: 代码应如下所示:

$(function() {
var $list, $newItemForm;
$list = $('ul');
$newItemForm = $("#newItemForm"); // Remember to use # to select by ID.

$newItemForm.on('submit', function (e) {
    e.preventDefault();
    // Get value from item field.
    var text = $('#itemField').val(); // Use # here as well.
    // Clear the item field.
    $('#itemField').val('');
    console.log(text);
    $list.append('<li>' + text + '</li>');

    if(text == "a") {
        alert("it works");
    }
});

});

If you don't use #, jQuery expects what follows to be an element type, for instance ul or span or the like. 如果您不使用#,则jQuery会期望以下元素类型,例如ul或span等。 If you want to select by class you need to prepend a . 如果要按班级选择,则需要在前面加一个。 in front of the class name, for instance ".classname". 在类名前面,例如“ .classname”。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM