开发者

IE8 and javascript object property, text

Using .text object property in JavaScript can produce unexpected results in IE8 (blank string or undefined even when it contains a value).

You can use .innerHTML object property as a workaround. IE8 seems to like this.

Or, for reliable cross-browser compatability you can use jquery instead to access an object's text property and I could have do so with: $(this).text() See the answer for a good jQuery solution.

Original Question: Is, 'text' a reserved javascript word in IE8? I am curious because I could not find any resource that states this.

*JavaScript (optionObj.innerHTML) Solution: *

// Look for a match in the section dropdown and select it.
$.each($('#' + mySelect + ' option'), function(key, optionObj) {

    // Switched 'optionObj.text' to 'optionObj.innerHTML' for cross-browser compatibility
    if (optionObj.innerHTML == strTextToMatch) {
        // Found a match
        $('#' + mySelect).val(optionObj.text);
        $('#' + mySelect).trigger('change');
    }
});
开发者_开发知识库

In IE8, optionObj.text would sometimes return a blank string, even when I could see in my debugger that it contained a value (I could see by expanding the optionObj object)! What was strange is that 10% of the time, optionObj.text would return the actual value other than a blank string. That being said, optionObj.innerHTML seems to work reliably.


No, text is neither a reserved word, nor a future reserved word, in JScript.

http://msdn.microsoft.com/en-us/library/0779sbks(v=vs.85).aspx


Edit OH, I see it now.

You're using the wrong each function — $.each() instead of .each().
You're also using .text instead of .text(). Fixes:

var $mySelect = $('#' + mySelect);
$mySelect.find('option').each(function()
{
    var $option = $(this),
        text = $option.text();
    if (text == strTextToMatch) {
        // Found a match
        $mySelect.val(text);
        $mySelect.trigger('change');
    }
});

but guess what: that's is totally unnecessary. This will suffice:

var $mySelect = $('#' + mySelect),
    newVal = $mySelect.find('option:contains(' + strTextToMatch + ')').val();
$mySelect.val(newVal).change();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜