jQuery函数val()不等同于"$(this).value=?"。

39
当我尝试使用$(this).value=""将文本输入设置为空(当单击时),这不起作用。我必须使用$(this).val('')
为什么?有什么区别?jQuery中val函数的机制是什么?
$(document).ready(function() {
    $('#user_name').focus(function(){
        $(this).val('');
    });
});
// error code: not working...
$(document).ready(function() {
    $('#user_name').focus(function(){
        $(this).value='';
    });
});
4个回答

85
你想要:
this.value = ''; // straight JS, no jQuery
或者
$(this).val(''); // jQuery

$(this).value = '' 表示将一个空字符串赋值给封装了this的jQuery对象的value属性,而不是this本身的value


17

$(this).value 试图调用 jQuery 对象的 'value' 属性,但该属性不存在。 原生 JavaScript 在某些 HTML 对象上确实有 'value' 属性,但如果您正在操作 jQuery 对象,则必须通过调用 $(this).val() 来访问值。


2
注意: $(this) 的类型是 JQuery 对象。
而且 $(this)[0] 的类型是 HTMLElement 对象。
那么: 如果你想在 HTMLElement 上应用 .val(),你可以添加这个扩展。
HTMLElement.prototype.val=function(v){
   if(typeof v!=='undefined'){this.value=v;return this;}
   else{return this.value}
}

然后:
document.getElementById('myDiv').val() ==== $('#myDiv').val()

并且
 document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')

العكس INVERSE :

相反地,如果您想将值属性添加到jQuery对象中,请按照以下步骤进行:

  1. 下载完整的源代码(非压缩文件),例如:http://code.jquery.com/jquery-1.11.1.js

  2. 在第96行之后插入一行,在其中添加此代码value:""以初始化此新属性 enter image description here

  3. 搜索 jQuery.fn.init,它几乎在2747行左右。

enter image description here

  1. 现在,为value属性分配一个值:(在返回语句之前添加this.value=jQuery(selector).val()enter image description here

现在尽情享受吧:$('#myDiv').value


1
一件你可以做的事情是这样的:

$(this)[0].value = "Something";

这使得jQuery能够返回该元素的JavaScript对象,并且您可以绕过jQuery函数。

这听起来有点傻,但你应该使用原始的CSS选择器,而不是this - Adam Fowler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接