是否在创建时立即设置了jquery对象的“内容”?

时间:2013-01-24 09:36:40

标签: javascript jquery

关于另一篇帖子:innerHTML works jQuery html() doesn't,我想问一下我在jQuery对象引用的div的内容是否在创建对象时立即设置。

JSF页面:

<!-- initialize script with the formId and the id of the input -->
<script type="text/javascript">
    $(document).ready(function(){
        mx.autocomp.overlay.init('formId', 'searchValue');
    });
</script>

<!-- input text that at "keyup" calls on sendRemoteCommand -->
<p:inputText
    id="searchValue"
    value="#{searchBean.searchValue}"
    onkeyup="sendRemoteCommand();" />

<!-- PrimeFaces remoteCommand that executes db search -->
<!-- and present result in "searchResult" div -->
<p:remoteCommand 
    name="sendRemoteCommand" 
    actionListener="#{searchBean.complete()}" 
    update="searchResult"
    oncomplete="mx.autocomp.overlay.handleOverlay();" />

<!-- PrimeFaces overlayPanel that is displayed if the search returned a result -->
<!-- i.e. the div "searchResult" has content ($searchResult.html() has content) -->
<p:overlayPanel 
    id="overlay" 
    widgetVar="overlayWid" 
    for="formId:searchValue" 
    showEvent="none">

    <h:panelGroup layout="block" id="searchResult">

        <!-- Content will be presented here after a p:remoteCommand is finished -->

    </h:panelGroup>

</p:overlayPanel>

如上所示,一旦页面准备就绪,脚本就会被初始化。

脚本(部分):

var formId;
var $searchValueComp;
var $searchResultComp;

function init(inFormId, inSearchValue){
    formId = inFormId;
    $searchValueComp = $("#"+inFormId).find("[id$="+inSearchValue+"]");
    $searchResultComp = $("#"+inFormId).find("[id$=searchResult]");
}

function handleOverlay(){
    var fn = window["overlayWid"];
    var result = document.getElementById($searchResultComp.attr("id")).innerHTML;

    if($searchValueComp.val().length==0){
        fn.hide();
    }

    // Test - This does not work as I get an empty alert
    alert($searchResultComp.html());

    // Test - This works.
    var $test = $("#"+formId).find("[id$=searchResult]");
    alert($test.html());

    // I need to check if the div: "searchResultComp" has any content. 
    // As I don't get $searchResultComp.html() to work, I'm forced to 
    // use the "getElementById" way instead. 
    if(result.length==0){
        fn.hide();
    }else{
        fn.show();
    }

}

如上所述,“init”中的jQuery对象似乎无法访问div的内容,而在“handleOverlay”中创建的jQuery对象则可以访问。

我的期望是jQuery对象的“html()”函数会实时检查内容,而不是 - 看起来 - 从创建时获取旧信息。因此我的问题是:

我通过jQuery对象引用的div的内容是仅在创建对象时设置的吗?

2 个答案:

答案 0 :(得分:0)

这取决于您何时拨打init()功能。例如,如果在DOM尚未就绪时调用它,则选择为空。

因此,无论何时使用$('#selector').find(),它都会为您提供在该确切时间选择的元素。如果你把它放在你的handleOverlay()中,它应该有效。

尝试习惯jQuery event delegation,你不必处理这类事情。

答案 1 :(得分:0)

这是因为变量$ searchResultComp是在init函数中设置的,jquery对象本身是动态的,但不是使用jquery对象的查询结果。

find()方法查找jquery对象的所有后代,这些后代与您指定的模式匹配作为find的条件,并将它们作为新的jquery对象返回。如果没有匹配的后代将返回没有内容的jquery对象。您可以通过提醒对象的长度来测试它,它应该为零。

因此在handleOverlay函数中,您需要重置$ searchResultComp以查找现在符合您条件的所有后代。