请解释跨浏览器字符串长度的差异

Please explain this difference in cross browser string.length

本文关键字:字符串 解释 浏览器      更新时间:2023-09-26

我在Firefox v6.0.2和IE7中运行这段代码。在Firefox中,我选择了单选按钮。然后单击"测试"。我得到的字符串长度为10。在IE7中,我得到字符串长度9

<script type="text/javascript">
    function TestMethod() {
        var name;
        var address;
        var city;
        var state;
        var zip;
        var indexor = 0;
        $('input[name=radioBtnSet1]:checked').parent().siblings().each(function (i, cell) {
            if (indexor === 0)
                name = $(cell).text();
            else if (indexor === 1)
                address = $(cell).text();
            else if (indexor === 2)
                city = $(cell).text();
            else if (indexor === 3)
                state = $(cell).text();
            else if (indexor === 4)
                zip = $(cell).text();
            indexor++;
        });
        alert(name.length);
        alert('FACILITY NAME: ' + '|' + name + '|');
    }
</script>
<input id="runTest" onclick="javascript:TestMethod();" type="button" value="Test"/>
<table id="someTable">
<thead>
    <tr>
        <th></th>
        <th>Header</th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th>Date</th>
    </tr>
</thead>
<tbody>
<tr>
    <td><input type="radio" value=" HHH VALUE" name="radioBtnSet1" /></td>
    <td style="text-align: left;"> HHH VALUE</td><td class="DisplayNone">200 SOME STREET DR</td>
    <td class="DisplayNone">CITY</td><td class="DisplayNone">TX</td>
    <td class="DisplayNone">75007-3726</td>
    <td style="padding-left: 1em;">9/30/2011</td>
</tr>
</tbody>
<tfoot>
    <tr>
        <th></th>
        <th></th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th class="DisplayNone"></th>
        <th></th>
    </tr>
</tfoot>
</table>

为什么?怎样才能使它们相等呢?

从本页的评论中可以看出,问题出在jQuery的text函数上。在IE 7中,它不保留前后空白。在FF中,确实如此。因此,IE 7和FF中的字符串和长度不同。

如果您需要空格,请尝试使用&nbsp;