1
//Html - page containing link to open dialog

<input type="text" value="something" id="inputbox_id" />
<a href="#" class="opendialog">Open</a>

//Javascript

.opendialog.click function 
{
$('.modaldialog').click(function(event) {
    $('<div id="dialogContainer"> </div>').appendTo('body');

   //ajax call to page.php, if successful then add output of page.php to 
   //dialogContainer div created above
   //page.php has a button and some javascript as below
}


//Html - content of page.php
<input type="button" id="button" value="I am button" />

//Javascript on page.php
// On click "#button" 
// $('#inputbox_id').val("Something New");

但它没有工作,而是我收到一个错误“inputbox_id is not defined”....

所以我将代码更改为

$('#input_box_id', 'body').val(); // didn't work

$('body').find('#input_box_id').val("some value"); //Worked

我的问题是——

为什么 $(selector, context) 选择器在这种情况下不起作用?可以使用选择正文然后找到所需的元素吗?你有什么更好的建议吗?

单击 #button 后如何关闭此对话框?

我感谢您的帮助!

更新

对话框关闭问题已解决 - 只需调用 $("#IdOfDialogContainer").remove();

4

1 回答 1

0
$('#input_box_id', 'body').val(); 

这种用法是错误的,你必须在第二个参数中给出 DOM 元素。像这样:

$('#input_box_id', document.getElementsByTagName('body')).val(); 

另一种方式是-您在帖子中提到的,

$(body).find('#input_box_id').val(); 

JQuery官方网页中已经提到过:

在内部,选择器上下文是用 .find() 方法实现的, *所以 $('span', this) 等价于 $(this).find('span').*

来源:http ://api.jquery.com/jQuery/

所以,你不需要按照我说的第一种方式来实现,不会有性能问题。

于 2012-06-20T18:05:52.807 回答