1

如下,假设我在 A.html 中有一个点击按钮来打开一个 ui 对话框,该对话框会将 B.html 作为内容加载。

那么,如果我想在用户单击对话框上的“确定”按钮后获取 B.html 中 id=inputName 的值,我该怎么办?我总是得到“未定义”。

抱歉,这可能是一个愚蠢的问题,因为我是 jQuery 新手。如果你能帮助我,我会非常感激。

一个.html


$(function(){
    $('#name').click(function(){
        var aaa = window.parent.$.dialog({
            buttons: {
                'ok': function(){
                    //get the value from B.html(ex.the value which id=inputName)
                    $aaa.dialog('close');
                }
            }
        });

        var link = 'B.html';
        aaa.load(link);
        aaa.dialog('open')
    });
}); //jquery code


<div>
    <input type="button" value="input your name" id='name'>
</div>  //html code

B.html


<input type="text" name="inputName" id="inputName"/>

4

2 回答 2

0

这里的问题是 .load() 是异步的。

一个可能的解决方案如下。关键是您只能在加载完成时弹出一个对话框,即在回调中。请注意,在下面的示例中,创建了一个不可见元素作为您加载的 HTML 的持有者。加载完成后,你可以遍历它的子元素或者从文档中获取你的元素:

<h1 id="dialogtest">Click me for a dialog!</h1>
<script type="text/javascript">
var myElementValue = null;
$(function(){
    $('#dialogtest').click(function(){
    var dialogElement = document.createElement("div");
    var link = 'B.html';
    $(dialogElement).load(
        link,
        function(responseText, textStatus, XMLHttpRequest) {
            alert('Load complete: ' + responseText + "; " + textStatus + ";\n " + dialogElement.outerHTML);
            var myDialog = $(dialogElement).dialog({
                autoOpen: false,
                buttons: {
                    'ok': function(){
                        // You can traverse the childNodes of dialogElement, or do just thie following.
                        // For example, this is the value of a text node:
                        myElementValue = document.getElementById("myElement").childNodes[0].data;
                        alert(myElementValue);
                        myDialog.dialog('close');
                    }
                }
            });
            $(myDialog).dialog('open'); // Can autoOpen it above instead
        }
    );
    });
}); //jquery code
</script>
于 2012-10-16T09:26:21.480 回答
0

实际上,我想通过 ajax 请求获取 B.html 中的值以用于 CGI。以另一种方式,我完成了这项工作,将以下代码添加到 B.html

<script type="text/javascript">
var okBtn = $('.ui-dialog-buttonpane').children("button:last");
okBtn.click(function(){ ajaxRequest(); });

function ajaxRequest() {
        var data
        data.name = $('#inputName').val();
        var url="(cgi link)";
        $.get(url,data);
        return;
}
</script>
于 2012-10-18T13:22:51.947 回答