关于另一篇文章:innerHTML works jQuery html() doesn't,我想问一下,当我创建一个对象时,是否立即设置了由jQuery对象引用的div的内容。是否在创建时立即设置jquery对象的“内容”?
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();
}
}
如上所述,在“初始化” jQuery对象似乎没有访问到div的内容,而在“handleOverlay”创建jQuery对象一样。我期望的是,jQuery对象的“html()”函数将实时检查内容,而不是 - 看起来 - 从创建时获取旧信息。因此,我的问题:
是否只有在创建对象时才引用jQuery对象的div的内容?
所以不可能创建一个jQuery变量,并且在它引用的对象(div)发生了任何变化后,查看这些变化? – nivis
在这种情况下,当您在init()中设置变量$ searchResultComp时,没有DOM内容供jquery返回,因为它尚未添加,所以对象为空。然后,当您在handleOverlay中请求对象的html()时,它将返回null。 –
感谢您的解释!我感到非常沮丧,无法理解发生了什么。 – nivis