如何使用jQuery和'this'来捕获更改的表单元素值

H. *_*nce 5 jquery onchange

我有以下代码,每次在我的Web表单中发生元素更改时都会起作用:

<!--

jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions

$(document).ready(function(){

    $(this).change(function(){
        alert('form element changed!');
    });

}); // end .ready()

//-->
Run Code Online (Sandbox Code Playgroud)

我一直在努力的是如何在触发更改事件时捕获表单字段元素 id,名称更改的值.

任何人都可以帮我解决这个问题吗?

谢谢!

**JAVASCRIPT文件**

// Sarfraz
$(this).change(function(){
   var id, name, value;
   id = this.id, name = this.name, value = this.value;
    alert('id=' + id); // this returns 'undefined'
    alert('name=' + name); // this returns 'undefined'
    alert('value=' + value); // this returns 'undefined'
});
//

// rjz
$(this).change(function(){
  var $this = $(this),
    id = $this.attr('id'),
    name = $this.attr('name'),
    value = $this.val();

    alert(id); // this returns 'undefined'
    alert(name); // this returns 'undefined'
    alert(value); // this returns blank
});

// Jamie
$(this).change(function(){
    var id = $(this).attr('id');
    var name = $(this).attr('name');
    var value = $(this).attr('value');

    alert('id=' + id); // this returns 'undefined'
    alert('name=' + name); // this returns 'undefined'
    alert('value=' + value); // this returns 'undefined'
});
//

//James Allardice
$(this).change(function(e) {
    var elem = e.target;
    alert('elem=' + elem); // this returns 'objectHTMLTextAreaElement'
});
//

// Surreal Dreams
$("#my-form input").change(function(){
    alert('form element changed!');
    var value = $(this).val();
    var id = $(this).attr("id");
    var name = $(this).attr("name");

    alert(id); // nothing happens
    alert(name); // nothing happens
    alert(value); // nothing happens
});
//

//Jamie - Second Try
$('.jamie2').each(function() {
    $(this).change(function(){
        var id = $(this).attr('id');
        alert(id); // nothing happens
    });
});
//
Run Code Online (Sandbox Code Playgroud)

Sur*_*ams 5

我想你从一开始就可能遇到问题:

$("#myform input").change(function(){
    alert('form element changed!');
    var value = $(this).val();
    var id = $(this).attr("id");
    var name = $(this).attr("name");
});
Run Code Online (Sandbox Code Playgroud)

您不想以$(this)开头,您需要选择要监视的输入.然后你可以在change()函数中使用$(this).

James Allardice指出,您可能使用$(this)引用该表单,而change()事件将捕获表单中的所有更改.我建议您更具体地定位更改的元素,这样您就不会捕获不需要或不想要的元素的更改事件,这可以消除意外行为.您可以使用类或表单选择器来定位它们:input.


Jam*_*ice 4

据我了解,它this指的是一个元素,并且您想要获取对触发事件form的该元素的后代的引用。form

如果这是正确的,您可以使用target事件对象的属性:

$(this).change(function(e) {
    var elem = e.target;
});
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例

在上面的代码中,elem将引用触发事件的元素。然后您可以访问该元素的属性,例如id

$(this).change(function(e) {
    var elemId = e.target.id;
});
Run Code Online (Sandbox Code Playgroud)