2013-04-05 90 views
8

在函數中,我需要檢查一個(div,span,p)是否包含任何.html元素,然後再嘗試刪除html並添加新內容。如何在刪除前檢查元素是否含有HTML? jQuery

不知道如何做到這一點...

我嘗試這樣做,但不工作:

// HERE below I tried to do a check to see if the div's have HTML, but did not work 
    if ($('.'+rowName+' div').html) { 
     $('.'+rowName+' div').html.remove(); 
     $('.'+rowName+' span').html.remove(); 
     $('.'+rowName+' p').html.remove(); 
    } 

全功能

// Create the Role/Fan rows 
function rowMaker (rowName, roleName) { 
    //alert(rowName+' '+roleName); 

    // HERE below I tried to do a check to see if the div's have HTML, but did not work 
    if ($('.'+rowName+' div').html) { 
     $('.'+rowName+' div').html.remove(); 
     $('.'+rowName+' span').html.remove(); 
     $('.'+rowName+' p').html.remove(); 
    } 

    // Blue button 
    $('.'+rowName+' div').append(roleName); 
    $('.'+rowName+' div').attr('id', 'blue-fan-'+roleName); 
    var blueButton = ('blue-fan-'+roleName); 
    console.log('blueButton = '+blueButton); 

    // Genres 
    $('.'+rowName+' span').append(roleType); 

    // Tags 
    $.each(role_Actor, function(index, item) { 
     $('.'+rowName+' p').append(item+', '); 
    }); 

    $('#'+blueButton).click(function() { 

     console.log('clicked blue button'); 

     // clears the role_Actor to be used to recapture checkboxes 
     role_Actor = []; 

     console.log('role_Actor = '+role_Actor); 

     //$('#modal-'+roleId).modal(); 
     $('#modal-'+roleId).modal({persist:true}); 
     return false; 
    }); 

} 
+0

如果元素有HTML,如果你只是要刪除它,它真的很重要嗎?爲什麼不直接用['.html'](http://api.jquery.com/html)替換內容? – 2013-04-05 02:27:31

+0

哦,因爲有些用戶會按下該按鈕,啓動該功能,藍色按鈕還沒有創建...所以沒有任何.html刪除和拋出和控制檯上的錯誤:(可能而不是刪除是否有某種明確的呼叫,我可以做?現在看嗯 – 2013-04-05 02:28:45

回答

12

html是方法不是屬性,你需要使用(),那麼你可以使用length String對象的屬性來檢查返回的html字符串的長度:

if ($.trim($('.'+rowName+' div').html()).length) { 
    // $('.'+rowName).find('div, p, span').remove(); 
    $('.'+rowName).find('div, p, span').empty(); 
} 

請注意,如果要更改元素的HTML內容,則不需要刪除它的當前html內容。方法html覆蓋當前的html內容。

5

檢查孩子的長度。

if($('.'+rowName+' div').children().length > 0) 
+1

'.children()'不會返回文本節點。 – jmar777 2013-04-05 02:31:28

+1

@ jmar777 ...我很確定這就是要點。 – 2014-12-09 19:08:16

1

嘗試

if ($('.'+rowName+' div').html().length > 0) { 
     $('.'+rowName+' div').empty(); 
     $('.'+rowName+' span').empty(); 
     $('.'+rowName+' p').empty(); 
} 
2

您可以使用.html()這(和佔空格):

var $row = $('.rowName'); 

if (!$row.find('div').html().trim().length) { 
    $row.find('div, span, p').empty(); 
} 
0

普通的香草的JavaScript應該做的伎倆。

if(document.querySelectorAll('.'+rowName+' div')[0].childElementCount > 0){ 
    console.log("found"); 
}