关于另一篇文章: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 的内容是否仅在创建对象时设置?
最佳答案
这是因为在init函数中设置了变量$searchResultComp,jquery对象本身是动态的,而不是使用jquery对象查询的结果。
find() 方法查找与您指定的模式匹配的 jquery 对象的所有后代作为查找条件,并将它们作为新的 jquery 对象返回。如果没有匹配的后代,它将返回一个没有内容的 jquery 对象。您可以通过提醒对象的长度来测试它,它应该为零。
因此在 handleOverlay 函数中您需要重置 $searchResultComp 以找到现在符合您的条件的所有后代。
关于javascript - jquery 对象的 "content"是在创建时立即设置的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498059/