过滤 DOM 中具有通用“类”名称的元素并在其上应用 CSS - JQuery

问题描述 投票:0回答:3

在 DOM 中,我可以过滤掉类名以特定单词开头的元素,这里是

answer_list_two cpts_
,结果如下。

$('[class^="answer_list_two cpts_"]') =>

[<div class=​"answer_list_two cpts_1_19234">​…​</div>​, <div class=​"answer_list_two cpts_2_19234">​…​</div>​, <div class=​"answer_list_two cpts_3_19234">​…​</div>​, <div class=​"answer_list_two cpts_4_19234">​…​</div>​, <div class=​"answer_list_two cpts_5_19234">​…​</div>​, <div class=​"answer_list_two cpts_1_19234">​…​</div>​, <div class=​"answer_list_two cpts_2_19234">​…​</div>​, <div class=​"answer_list_two cpts_3_19234">​…​</div>​, <div class=​"answer_list_two cpts_4_19234">​…​</div>​, <div class=​"answer_list_two cpts_5_19234">​…​</div>​, <div class=​"answer_list_two cpts_1_19235">​…​</div>​, <div class=​"answer_list_two cpts_2_19235">​…​</div>​, <div class=​"answer_list_two cpts_3_19235">​…​</div>​, <div class=​"answer_list_two cpts_1_19235">​…​</div>​, <div class=​"answer_list_two cpts_2_19235">​…​</div>​, <div class=​"answer_list_two cpts_3_19235">​…​</div>​]

由此,我想获取一个元素,找到它的

class name
,找到具有相同类名的另一个元素,比较两个 DIV 元素的 height
,并将较大的高度值应用于两个 DIV 元素。 

如何编写 jQuery 代码来实现相同的功能?

javascript jquery html css
3个回答
4
投票
尝试

var filtered = {}, $els = $('.answer_list_two[class*="cpts_"]'); $els.each(function () { var clazz = this.className.match(/cpts_\d+_\d+/)[0]; if (filtered[clazz]) { return; } var height = 0; $els.filter('.' + clazz).each(function () { var h = $(this).height(); if (height < h) { height = h; } }).height(height); filtered[clazz] = true; })

演示:

小提琴


2
投票
以此为开始(未经证实),如果我应该改变一些东西,现在就让我来。

var classs; $('[class^="answer_list_two cpts_"]').each(function(index, val) { classs = val.attr('class'); $('.'+classs).each(function(index2, val2) { if(val.height() > val2.height()){ val2.css('height', val.height()); } else { val.css('height', val2.height()) } }); });
    

1
投票
你只需做一些类似比较的事情:

function compareHeight($el, $el2){ var h1 = $el.height(); var h2 = $el2.height(); var h = h1 > h2 ? h1 : h2 $el.css('height', h); $el2.css('height', h); } var $items = $('.class'); if($items.length > 1){ compareHeight($items.eq(0), $items.eq(1)); }

我不确定您想要使用什么逻辑来获取元素,但是可以根据需要选择它们并将它们传递到该函数中,并且它应该按照您提到的方式比较和设置高度

© www.soinside.com 2019 - 2024. All rights reserved.