我刚刚发现了一个......古怪? ...在我们的一个脚本中。在该方法中,我们有以下的JavaScript代码段:
if (inside)
elem.insertBefore(c, null);
else
elem.parentNode.insertBefore(c, elem.nextSibling);
使用用下面的命令控制台(铬)时
,我得到如下结果:
的Javascript:
elem.parentNode -> undefined
jQuery的
$(elem).parent(); -> <div class="btn-holder-right"><input onclick=" return handle_qa_submit_comment(5, 6, this);" value="Submit Comment" title="" type="submit" class="btn btn-community"></div>
我觉得这是奇怪的想知道为什么会发生这种情况。有什么建议?
- 首先按钮的onclick
处理程序发送按钮本身在onclick
事件中列出的功能
<input onclick=" return handle_qa_submit_comment(5, 6, this);" value="Submit Comment" title="" type="submit" class="btn btn-community">
函数包含了一些Ajax它做了几件事情上我们的网站,如提交评论
function handle_qa_submit_comment(postId, parentPostId, elem){
var ajaxUrl = '../forum/qa-include/app/handler.php';
var data = {
action : 'add_comment',
data :
{
'postId' : postId,
'parentPostId' : parentPostId,
}
};
try
{
$.ajax({
url: ajaxUrl,
data: JSON.stringify(data),
contentType: 'application/json',
async: true,
type: 'POST'
}).done(function(jqxhr,textStatus){
if (jqxhr !== 'true' && textStatus !== 'success'){
return handle_qa_submit_comment_failed(403, null);
}
else {
qa_submit_comment(postId, parentPostId, $(elem)); // calls
}
}).error(function(){
return handle_qa_submit_comment_failed(404, null);
});
}
catch (exception)
{
return handle_qa_submit_comment_failed(500, exception);
}
}
当AJAX完成:
function qa_submit_comment(questionid, parentid, elem)
{
...do stuff...
qa_show_waiting_after(elem, false);
}
最后:
function qa_show_waiting_after(elem, inside)
{
var c = 'some html....';
if (elem && !elem.qa_waiting_shown) {
if (inside)
elem.insertBefore(c, null);
else
elem.parentNode.insertBefore(c, elem.nextSibling); // fail here because elem.parentNode is undefined. when I test $(elem).parent() it finds the actual parent.
}
}
请你可以发表elem如何初始化?这可能是元素还没有在DOM中,例如你正在JQuery中构造HTML,并且直到它实际插入到DOM中,DOM才有它自己的表示形式? – 2015-03-02 14:00:27
你问了。这是一系列方法调用,在'qa_show_waiting_after'结束时,'elem'肯定包含按钮,parentNode显示'undefined'和'$(elem).parent()',当断点处于elem时,直接键入控制台。 parentNode.insertbefore()实际返回元素的父节点。另外,我省略了一些敏感的代码,以供公众观看:) – Eon 2015-03-02 14:13:05
试图阻止发布代码墙 – Eon 2015-03-02 14:22:15