我有以下 html 代码:
<div class="display_label">Work phone:</div>
<div class="display_work_phone display_attr"></div>
<div class="display_label">Email:</div>
<div class="display_work_phone display_attr"></div>
<div class="display_label">Comment:</div>
<div class="display_comment display_attr"></div>
可能,工作电话和评论有时会是空的,所以我想用“-”字符替换“空”。我试图检查它的长度是否为0,但我不知道如何让它工作。我想检查每个 div 的内容,如果它没有值,请将其替换为类名“display_attr”。
最佳答案
您可以使用:empty-selector
$('.display_work_phone, .display_comment').filter(':empty').html('-')
注意:如果节点包含空文本节点,则空选择器将不起作用,在这种情况下,您可以自己编写一个简单的过滤器,例如
$('.display_work_phone, .display_comment').filter(function () {
return $.trim($(this).text()).length == 0
}).html('-')
关于javascript - 将一个字符放入具有指定类别的空 div-s 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866482/