2

这是我的代码: HTML 部分

<form id="myform" action="whatever.php">
    <lable name="text">enter text</label>
    <input id="in" type="text" />
    <input id="in2" type="text" />
    <input type="submit" id="submit" />
</form>

jQuery代码:

 (function($){
    $('#myform').on('click', '#submit', function(e) {
        var val = $(this).find('#in').val(); 
        $('ol.list').append('<li class="text-dark"><p>' + val + '.</p></li>');
        e.preventDefault();
    });
})(jQuery);

输出:

1.未定义。

2.未定义。

3.未定义。

4

2 回答 2

1

On your code this inside the callback function points to the button with id #submit not the form itself. You could just use the submit event, and your code will work fine

(function($){
    $('#myform').on('submit', function(e) {
         e.preventDefault();
        var val = $(this).find('#in').val(); 
        $('ol.list').append('<li class="text-dark"><p>' + val + '.</p></li>');
    });
})(jQuery);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
<ol class="list"></ol>
<form id="myform" action="whatever.php">
    <label name="text">enter text</label>
    <input id="in" type="text" />
    <input id="in2" type="text" />
    <input type="submit" id="submit" />
</form>
	
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

</body>
</html>

于 2019-01-07T07:27:36.550 回答
0

然后带有 idin的元素是元素的子元素而form不是submit按钮。

您需要通过获取父表单元素来执行以下操作,然后在该元素中找到您的元素,因为您的输入元素不在提交按钮中:

var val = $(this).closest("form").find('#in').val(); 

$(this).closest("form")将选择表单,然后find('#in')将选择具有 id 的元素,in然后val()将获取它的值。

查看工作中的演示小提琴

于 2019-01-07T07:19:25.893 回答