如何在jQuery中定位含input_container子元素的card-body类并修改样式
解决方案
现有代码问题梳理
- 语法错误:代码中使用了中文全角引号(‘’、“”),JS无法识别,需要全部替换为英文半角引号(''、"")
hasClass()方法传参不需要加类选择器前缀.,原代码写hasClass('.input_container')是错误写法,正确参数是'input_container'- 第二种写法的逻辑错误:查询
.input_container时没有限定在当前遍历的.card-body范围内,会全局匹配页面所有同类元素,导致判断逻辑完全失效 - 两个判断条件需要是「或」的关系,满足任意一个就执行样式修改
正确实现代码
$(function(){ $("#Color").on("change", function(){ const selectedColor = $(this).val(); $('.card-body').each(function(){ const $currentCard = $(this); // 判断条件1:当前card-body存在类名为input_container的直接子元素 const hasInputChild = $currentCard.children('.input_container').length > 0; // 判断条件2:当前card-body的直接子元素存在文本内容为…的节点 const hasEllipsisText = $currentCard.children().filter(function() { return $(this).text().trim() === '…'; }).length > 0; if (hasInputChild || hasEllipsisText) { $currentCard.css('background-color', selectedColor); } }); }); });
该实现不需要修改fileA的代码新增ID,只会命中符合你要求的
.card-body元素,不会影响页面其他位置使用的同类元素样式。
内容的提问来源于stack exchange,提问作者hika
相关产品推荐
相关产品推荐

