Jquery .val()更改dom中的值,但不更改网页上的值

时间:2012-11-17 02:14:29

标签: jquery dom

我有一块调试代码MyPartialContent.ascx :(从jquery ajax调用返回并使用$(“#container”)插入DOM .val(html);其中html是下面的代码块

 <input type"text" id="mydebugtextbox" value="world"/> -- shows a text box on web page with "world"

$("#mydebugtextbox").val("hello"); 
-- Should set value to "hello";

alert($("#mydebugtextbox").val()); 
-- should alert "hello" and it does but 
-- the textbox on the page still shows "world"

这仅在最初加载页面时发生。如果我点击f5或刷新页面,那么一切都按预期工作。

我迷路了。

3 个答案:

答案 0 :(得分:2)

jsBin demo

只需改变
mydegugtextbox

mydebugtextbox

如果您的语法正确,请确保将代码包装到ready函数中:

$(function(){ // DOM is ready

     $("#mydebugtextbox").val("hello");
     alert($("#mydebugtextbox").val()); 

});

确保您的元素已映射并准备好进行操作

答案 1 :(得分:1)

您确定整个DOM页面中只有1个带有该ID的输入框吗? 如果您有2个输入框,则只会更新第一个

参见此示例, http://jsfiddle.net/fedmich/hMqSq/


prev answer ...

假设没有拼写错误,并且您将代码置于页面加载

$(function() {  
//code here
});

您确定没有自动填充输入框的插件吗? 您使用的浏览器是什么?

答案 2 :(得分:0)

它不起作用,因为您在第一个选择器中拼错了debug

$("#mydegugtextbox").val("hello");
        ^

一旦你解决了这个错误,它就可以正常工作:http://jsfiddle.net/NMFEs/1/