简体   繁体   English

输入值的jQuery对话框脚本

[英]jQuery dialog scripts for input val

I have a bit of a problem with a jQuery dialog and the way scripts are handled. 我在jQuery对话框和脚本处理方式方面存在一些问题。

In the dialog html, I have 在对话框html中,我有

<input id="test"> 

If I do 如果我做

<script type="text/javascript>
   $('#test').val("haha")
</script>

after the input, it shows up. 输入 ,它显示了。 If I put it before , it doesn't work. 如果我把它放在前面 ,那是行不通的。 Now the problem is I'm trying to change the value of $('#test') using a click trigger, and I can't! 现在的问题是我试图使用单击触发器更改$('#test')的值,但我做不到!

   $('.testbutton').click(function() { 
          alert();      
          $('#test').val("haha");
    });

The alert works, and the initial val replacement works, which means there aren't any duplicate or missing input areas. 警报起作用,并且初始val替换起作用,这意味着没有重复或缺少输入区域。

The total script as it is now, not working: 现在的总脚本不起作用:

<input type="button" class="testbutton" />
<input type="text" size="10" id="test" name="test" value="">

 $('#test').val("currentvalue"); // This works
       $('.testbutton').click(function() { 
              alert();      
              $('#test').val("haha");
        });

Update The dialog shows the correct value in #test once the dialog is closed and then reopened. 更新一旦关闭然后重新打开对话框,该对话框将在#test中显示正确的值。 Could this be something I'm missing? 这可能是我所缺少的吗?

Put your jQuery code into $(document).ready(function () {...your code...}) . 将您的jQuery代码放入$(document).ready(function () {...your code...}) This will make it executed after browser creates DOM tree for your page. 这将使其浏览器为您的页面创建DOM树之后执行。 Otherwise javascript is not able to search/manipulate DOM elements correctly. 否则,javascript无法正确搜索/处理DOM元素。 It will look as following: 它将如下所示:

$(document).ready(function () {
    $('.testbutton').click(function() { 
          $('#test').val("haha");
    });
});

Update: 更新:

If your HTML code is loaded dynamically, then use live to bind event handler: 如果您的HTML代码是动态加载的,则使用live绑定事件处理程序:

$(document).ready(function () {
    $('.testbutton').live("click", function() { 
          $('#test').val("haha");
    });
});

I guess you should wrap your code inside of a $(function() { //code here }); 我猜您应该将代码包装在$(function(){//此处的代码})内; to make sure your code is run only when your DOM is ready. 以确保仅在DOM准备就绪时才运行代码。

The problem ended up being the # in test. 问题最终成为测试中的#。 For some reason the replacement works with a class identifier instead of a id identifier. 由于某种原因,替换使用类标识符而不是ID标识符。 I suppose it's because the # will replace only one instance, and for some reason that I have yet to discover, there is more than one instance of the dialog (or a hidden one). 我想这是因为#将仅替换一个实例,并且由于我尚未发现的某些原因,该对话框有多个实例(或隐藏的实例)。

Thanks for all your suggestions! 感谢您的所有建议!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM