Javascript 如何在删除之前检查元素中是否包含HTML?jQuery
在函数中,我需要检查a(div,span,p)是否包含任何.html元素,然后再尝试删除html并添加新内容 不知道怎么做 我试过这个,但不起作用:Javascript 如何在删除之前检查元素中是否包含HTML?jQuery,javascript,jquery,html,remove-if,Javascript,Jquery,Html,Remove If,在函数中,我需要检查a(div,span,p)是否包含任何.html元素,然后再尝试删除html并添加新内容 不知道怎么做 我试过这个,但不起作用: // 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();
// 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;
});
}
html
是方法而不是属性,您需要使用()
,然后您可以使用String对象的length
属性来检查返回的html字符串的长度:
if ( $.trim( $('.'+rowName+' div').html() ).length ) {
// $('.'+rowName).find('div, p, span').remove();
$('.'+rowName).find('div, p, span').empty();
}
请注意,如果要更改元素的HTML内容,则无需删除该元素的当前HTML内容
html
方法覆盖当前html内容。检查子项长度
if($('.'+rowName+' div').children().length > 0)
试一试
您可以为此使用.html()
(并考虑空格):
普通的JavaScript也应该做到这一点
if(document.querySelectorAll('.'+rowName+' div')[0].childElementCount > 0){
console.log("found");
}
这样做:
var elementExists = $('.'+rowName+' div').html();
if (elementExists) { ... }
如果要删除元素,那么该元素是否包含HTML真的很重要吗?为什么不完全用替换内容呢?哦,因为有些东西用户会点击该按钮,启动该功能,而蓝色按钮还没有创建。。。因此,没有任何.html要删除,并在控制台上抛出和出错:(可能不是删除,而是我可以进行某种明确的调用?嗯,现在看
。children()
不会返回文本节点。
if(document.querySelectorAll('.'+rowName+' div')[0].childElementCount > 0){
console.log("found");
}
var elementExists = $('.'+rowName+' div').html();
if (elementExists) { ... }