Can someone explain this seeming inconsistency in jQuery/Javascript?? (trailing brackets inconsistency on reads)
So, in my example below, "InputDate'" is an input type=text, "DateColumn" is a TD within a table with a class of "DateColumn".
Read the value of a discreet texbox:
var inputVal = $('#InputDate').val();
Read the value of a div within a table....
This works:
$('#theTable .DateColumn').each(function() {
var rowDate = Date.parse($(this)[0].innerHTML);
});
This doesn't:
$('#theTable .DateColumn').each(function() {
var rowDate = Date.parse($(this)[0].innerHTML());
});
The difference is the "()" after innerHTML. This behavior seems syntactically inconsistent between how you read a value from a textbox and how you read it from a div. I'm ok with sometimes, depending on the type of control, having to read .val vs .innerHTML vs.whateverElseDependingOnTheTypeOfControl...but this example leads me to believe I now must also memorize whether I need trailing brackets or not on each property/method.
So for a person like me who is relatively new to jQuery/Javascript....I seem to have figured out this particular anomaly, in this instance, but is there 开发者_StackOverflowa convention I am missing out on, or does a person have to literally have to memorize whether each method does or does not need brackets?
innerHTML
is javascript, and is a property of an element. If you'd like to stick with the jQuery version of doing things, use html()
:
$('#theTable .DateColumn').each(function() {
var rowDate = Date.parse($(this).html() );
});
edit: a bit more clarification about your concerns. jQuery is pretty consistent in it's syntax. Basically, most of the methods you find allow read/write access by adjusting the parameters passed to the method.
var css = $('#element').css('color'); // read the color of the element
$('#element').css('color', 'red'); // set the color to "red"
var contents = $('#element').html(); // grab the innerHTML of the element
$('#element').html('Hello World'); // set the innerHTML of this element
.innerHTML is a property of the element not a method.
Property reference Example: object.MyProperty
Method Example: object.SomeFunction();
精彩评论