【发布时间】:2012-03-06 19:36:15
【问题描述】:
每当我的网络表单中发生元素更改时,我都有以下代码:
<!--
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()
//-->
我一直在苦苦挣扎的是如何捕获 表单字段元素 id、name 和 changed value 何时触发更改事件。
谁能帮我解决这个问题?
谢谢!
** 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
});
});
//
【问题讨论】:
-
在您的示例中
this是什么? -
"this" 是 javascript 中的保留字,对吗?
-
是的,但它的含义是上下文相关的。
-
您通常在与所选元素相关的代码中使用 $(this),例如,在事件处理程序中引用具有事件的元素。
-
@Dr.DOT,当在 jQuery 事件处理程序(和其他一些方法)范围之外引用时,
$(this)通常是无效的(除非您将其设置为其他内容)。您应该改用选择器,如 Surreal Dreams 的回答所示。