jquery function val() is not equivalent to “$(this).value=”?

后端 未结 4 2116
礼貌的吻别
礼貌的吻别 2020-12-01 05:28

When I try to set a text input to blank (when clicked) using $(this).value=\"\", this does not work. I have to use $(this).val(\'\').

Why?

相关标签:
4条回答
  • 2020-12-01 05:41

    $(this).value is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val().

    0 讨论(0)
  • 2020-12-01 05:58

    Note that :

    typeof $(this) is JQuery object.

    and

    typeof $(this)[0] is HTMLElement object

    then : if you want to apply .val() on HTMLElement , you can add this extension .

    HTMLElement.prototype.val=function(v){
       if(typeof v!=='undefined'){this.value=v;return this;}
       else{return this.value}
    }
    

    Then :

    document.getElementById('myDiv').val() ==== $('#myDiv').val()
    

    And

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

    العكس INVERSE :

    Converselyو if you want to add value property to jQuery object , follow those steps :

    1. Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .

    2. Insert Line after L96 , add this code value:"" to init this new prop enter image description here

    3. Search on jQuery.fn.init , it will be almost Line 2747

    enter image description here

    1. Now , assign a value to value prop : (Before return statment add this.value=jQuery(selector).val()) enter image description here

    Enjoy now : $('#myDiv').value

    0 讨论(0)
  • 2020-12-01 06:01

    You want:

    this.value = ''; // straight JS, no jQuery
    

    or

    $(this).val(''); // jQuery
    

    With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

    0 讨论(0)
  • 2020-12-01 06:05

    One thing you can do is this:

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

    This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

    0 讨论(0)
提交回复
热议问题