我通过 DOMElement 对象以编程方式更新 WebKit Web View 上的 DOM - 对于复杂的 UI,我添加的任何元素通常都有一个 Javascript 组件。这就要求更新完成时需要得到通知——有这样的事件吗?我知道常规 div 不会触发 onload
或 onready
事件,对吗?我的另一个假设(可能是完全错误的)是 DOMElement 更新不是同步的,所以我不能做这样的事情并确信它会与 DOM 中实际的标签相匹配:
DOMElement *displayNameLabel = [document createElement:@"div"];
[displayNameLabel setAttribute:@"class" value:@"user-display-name"];
[displayNameLabel setTextContent:currentAvatar.avatarData.displayName];
[[document getElementById:@"user-card-content"] appendChild:displayNameLabel];
id win = [webView windowScriptObject];
[win evaluateWebScript:@"javascriptInstantiateLabel()"];
这是真的吗?
我已经在 html 正文中使用了 jQuery,所以我不介意通过“live”订阅特定类的事件集。我想我也许可以做这样的事情:
$(".some-class-to-be-added-later").live( "ready", function(){
// Instantiate some fantastic Javascript here for .some-class
});
但到目前为止还没有经历过任何快乐。当元素位于 DOM 中时,双方(objective-c 因为我不以编程方式触发 Javascript 加载后或 Javascript)有什么方法可以收到通知吗?
编辑:根据Anurag的回答,这是我想出的代码(有效):
function onButtonPanelChange() {
console.log( "Button panel subtree modified", 7 );
$(".panel-button").each( function(){
console.log( "Button found " + $(this).attr( "class" ), 7 );
if( !$(this).hasClass( "processed" ) ){
$("#bottom-button-panel").unbind( "DOMSubtreeModified" );
if( $(this).hasClass( "chat" ) ){
console.log( "Found chat button, instantiating", 7);
var chat_button = new Button( $(this), chat_button_def );
$(this).addClass( "processed" );
}
else if( $(this).hasClass( "get" ) ){
var chat_button = new Button( $(this), get_button_def );
$(this).addClass( "processed" );
}
$("#bottom-button-panel").bind( "DOMSubtreeModified", onButtonPanelChange );
console.log( "Done with button change, rebinding", 7 );
}
});
}
$(document).ready( function(){
$("#bottom-button-panel").bind( "DOMSubtreeModified", onButtonPanelChange);
});
请注意,您需要取消绑定(bind)事件,因为每个后续更改都会触发另一个事件,然后再触发另一个事件。
最佳答案
查看一小时前提出的类似问题 - Is there a JavaScript/jQuery DOM change listener?
要监听元素上的更改,请使用以下内容:
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
我还没有通过 Objective-C 编写 DOM 脚本,所以不知道是否有办法使用 Objective-C 包装器订阅 DOM 事件。
DOMSubtreeModified
修改事件适用于 iPhone。刚刚使用 this example 进行了测试。
关于javascript - 当 Objective-C dom 更新准备好从 webview 启动时收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2844781/