.prop() VS .val() .Setting an input text value with jQuery

后端 未结 6 1616
栀梦
栀梦 2021-01-05 12:42

After reading (the interesting) .prop() vs .attr() and jQuery Performance : attributes doubt arise in my mind about what is better to use: .prop() or .val() ? I want to set

6条回答
  •  粉色の甜心
    2021-01-05 13:07

    You want to use val(). That's what the function is for, specifically for the value of the input.

    It's also quicker to write, easier to understand and while using val, you can change the value multiple times if need be.

    Your chart says

    Higher is better

    and val() higher.

    Also, like you've already quoted,

    The .val() method should be used for getting and setting value.

    This means that unless you're dealing with disabled properties, use:

    $('input').val();
    

    Also as a side note, the link you posted, after running tests, shows that val() is faster than prop().

    Since you LOVE to show some graphs and pictures, i'm going to add some:

    Taken from this link

    Pure JS is better

    Pure JS is better if you're arguing over speed.

提交回复
热议问题