문제

I once saw a text about Jquery stating that in Jquery some properties have different names. I think it was the value property that is accessed in Jquery as val or something like that. Does JQuery do this a lot? Is a common practice of Jquery to change properties names?

도움이 되었습니까?

해결책

jQuery does not change any property names.

jQuery implements it's own methods on jQuery objects. Those are completely separate from DOM properties or DOM methods.

For example, you can retrieve the value of any input control from a jQuery object using the .val() method. Internally, the .val() method on the jQuery object accesses the contents of the DOM object (perhaps using the .value property), but it is not replacing that DOM property in any way. It is still there is you choose to use it instead.

Similarly, jQuery has a .html() method that returns the innerHTML of an object. Again, this is jQuery method on a jQuery object and does not replace the DOM property innerHTML in any way.

Here are some code examples to illustrate:

<input id="test" type="text">
<div id="title">This is my Title</div>

Using plain javascript:

var text = document.getElementById("test").value;
var title = document.getElementById("title").innerHTML;

Using jQuery:

var text = $("#test").val();
var title = $("#title").html();

Notice that both the jQuery ways are method calls, not properties.

Even when using jQuery objects, you could get the DOM object out of the jQuery object using the .get(n) method and use the DOM property, though there usually isn't a reason to do so:

var text = $("#test").get(0).value;
var title = $("#title").get(0).innerHTML;

다른 팁

jQuery doesn't change property names. jQuery returns jQuery instances not dom elements.

If you do $thing[0].value it will work. If you do $thing.prop("value") it will work.

If you use $thing.val(); which is jQuery's val method (which is "kind" of like val but does a bunch of weird edge case magic as well) then it will "probably" return the value of the wrapped dom element.

Not that I'm aware of, the case of val is because it let's you set or get the value of all form fields (textfields, radio buttons, checkboxes, textareas, etc.) something that's not possibly simply by doing input.value in all cases.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top