【问题标题】:jquery-problem using val() in IE6在 IE6 中使用 val() 的 jquery 问题
【发布时间】:2009-11-14 02:47:48
【问题描述】:

我正在尝试使用 jquery 更新 textarea 的值,如下面的代码所示:

<button type="button" onclick="setLine();">Set</button>
<button type="button" onclick="showLine();">fire!</button><p></p>
    <textarea id="hello">

    </textarea>
    <script type="text/javascript">
            $('#hello').val("hi there");
        </script>
    <script type="text/javascript">
        function showLine()
        {
            alert($('#hello').val());
        }
        function setLine()
        {
            $('#hello').val('foo');
        }
    </script>

此代码在除 IE6 之外的所有主流浏览器中都能正常运行。

在 Ie6 中,文本区域不会随着按钮单击而更新,并且警报会给出空白/空字符串。但是在其他浏览器中,单击“set”会将其更改为“foo”,然后会显示在警告框中。

有谁知道为什么这是特定于该浏览器的,或者代码可能有什么问题?我怀疑.val()

任何帮助将不胜感激。

【问题讨论】:

  • 这是您在 jsbin 上的示例:jsbin.com/ivaso 我没有方便的 IE6 来测试它。
  • 在 IE6 中尝试过,“按原样”完美运行
  • 你用的是什么版本的jQuery?

标签: jquery internet-explorer-6


【解决方案1】:

你应该在 document.ready 事件中调用 val():

$(document).ready(function() {

    $('#hello').val("hi there");

});

为了说明清楚:我只是在谈论对 val() 的第一次(全局)调用。函数声明不应在 document.ready 函数中。

【讨论】:

  • 只要在 textarea 之后加载脚本,应该没问题,尽管您的观点可能仍然有效。
  • 我遇到了 IE 问题,即使脚本是在 HTML 元素之后加载的。
【解决方案2】:

我认为你必须使用 .html() 而不是 .val() ...试着说出发生了什么?

【讨论】:

  • 当我使用 .html() 时,它会从屏幕上删除所有内容并将代码添加到新的空白页面中
  • 我希望你能详细解释你为了让它工作而摆弄了什么。我也有类似的问题。
【解决方案3】:

我不知道为什么你的代码不能在 IE6 中工作,但它不是正确的 jQuery。 我现在无法对此进行测试,但这应该可以进行一些更改:

<button type="button" id="setline">Set</button>
<button type="button" id="showline">fire!</button>

<textarea id="hello"></textarea>

<script type="text/javascript">
    $(document).ready(function(){
       $('#hello').val("hi there");

       $('#showline').click(function()
       {
           alert($('#hello').val());
       });

       $('#setline').click(function()
       {
           $('#hello').val('foo');
       });
   });

按钮在 jQuery 中不应该有 onclick 事件,你应该像上面显示的那样绑定它们。 并且始终使用 document.ready!

【讨论】:

  • 拥有 onclick 属性没有任何问题,即使在使用 jQuery 时也是如此。当然,最好使用jQuery的事件处理,但“老”的风格不一定是错的。
【解决方案4】:

您是否有多个 id 为“hello”的元素?

【讨论】:

  • 好的,但上面的代码在 IE6 中工作。试试jsbin.com/ivaso(正如 altCognito 建议的那样)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多