別の投稿に関連して: 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 の内容は、オブジェクトの作成時にのみ設定されますか?