javascript - 如何在删除之前检查元素中是否包含 HTML?查询

标签 javascript jquery html remove-if

在一个函数中,我需要在尝试删除 html 和添加新内容之前检查 (div, span, p) 中是否包含任何 .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();
        $('.'+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 内容。

关于javascript - 如何在删除之前检查元素中是否包含 HTML?查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824886/

相关文章:

javascript - 如何在 d3 中以编程方式调用 "click"事件?

javascript - 具有分层图像的 Canvas 手电筒效果

javascript - 如何在 iframe 加载网站时显示加载 gif?

javascript - Jquery 切换具有特定类的最接近的项目

jquery - 使用 CSS 和 JQuery 创建组织结构图

php - 为什么这个ajax脚本不使用ajaxRequest.open调用后端php?

html - 如何在悬停时使宽度过渡平滑?

javascript - 无法在 Axios 中取消 POST

javascript - 使用 JavaScript 一次只显示一个 div

javascript - 通过 JavaScript 更改 url(无哈希标签)