我剛剛發現了一個......古怪? ...在我們的一個腳本中。在該方法中,我們有以下的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