在jQuery中设置textarea的值

时间:2010-08-24 16:37:52

标签: javascript jquery sharepoint

我正在尝试在SharePoint中设置表单字段的默认值,并且在使用IE中的代码时遇到一些麻烦。我已经成功测试了Firefox和Chrome。任何想法为什么IE不会设置值?

<script type="text/javascript" src="http://www.qg.com/shared/cache/jquery/142/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
    setTimeout("setDefaultText()", 500);    
    function setDefaultText()
    {   
        var text = "Param 1:\n\nParam 2:\n\nParam 3:";

        var r1text = $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val();
        var r2text = $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl10_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val();

        if((r1text + "").length == 0)
        {
            $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val(text);
        }

        if((r2text + "").length == 0)
        {
            $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl10_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val(text);
        }
    }
</script>

1 个答案:

答案 0 :(得分:2)

setTimeout()的目的是什么?

如果您正在尝试确保加载DOM,那么您应该这样做:

$(function() {   
        var text = "Param 1:\n\nParam 2:\n\nParam 3:";

        var r1text = $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val();
        var r2text = $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl10_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val();

        if((r1text + "").length == 0)
        {
            $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val(text);
        }

        if((r2text + "").length == 0)
        {
            $("#ctl00_m_g_94a22119_a2e7_408c_aa27_c680b509802d_ctl00_ctl04_ctl10_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val(text);
        }
});

我猜这个DOM没有在500毫秒内加载,而你的.val()正在给你undefined,所以对于+ "",你最终得到了字符串"undefined"