jQuery Цикл через каждый div
Я уверен, что это будет очень простой ответ для вас, и я тоже довольно похож на такой цикл.
Я пытаюсь выполнить по существу те же вычисления на двух отдельных div, но присваивая каждому значению ширины CSS каждому идентификатору, основанному на количестве найденных изображений. Расчеты, которые я выполняю, на самом деле не имеют отношения к моей проблеме, но я все равно их ввел, потому что это фактический код, с которым я работаю.
Вот разметка...
<div id ='test1' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
<div id ='test2' class='target'>
<div class='scrolling'>
<img/>
<img/>
<img/>
</div>
</div>
Ниже мой текущий jQuery, который работает отлично, но он неэффективен, потому что я должен написать еще один кусок кода для каждого добавленного div. Как я могу стандартизировать это так, чтобы он проходил через каждый div с классом цели? благодаря
/* Measure the width of each image. */
test1 = $('#div1 .scrolling img').width();
test2 = $('#div2 .scrolling img').width();
/* Find out how many images there are. */
test1img = $('#div1 .scrolling img').length;
test2img = $('#div2 .scrolling img').length;
/* Do the maths. */
final1 = (test1 * test1img)*1.2;
final2 = (test2 * test2img)*1.2;
/* Apply the maths to the CSS. */
$('#div1 .scrolling').width(final1);
$('#div2 .scrolling').width(final2);
Ответы
Ответ 1
Как это:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
$(this)
.target
$(this)
относится к текущему .target
который будет зацикливаться. Внутри этого .target
я ищу. .scrolling img
и получить ширину. А потом продолжайте...
Изображения с разной шириной
Если вы хотите рассчитать ширину всех изображений (когда они имеют разную ширину), вы можете сделать это следующим образом:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
Ответ 2
Вы правы, что это связано с циклом, но это, по крайней мере, упрощено с помощью метода each()
:
$('.target').each(
function(){
// iterate through each of the '.target' elements, and do stuff in here
// 'this' and '$(this)' refer to the current '.target' element
var images = $(this).find('img'),
imageWidth = images.width(); // returns the width of the _first_ image
numImages = images.length;
$(this).css('width', (imageWidth*numImages));
});
Рекомендации:
Ответ 3
$('div.target').each(function() {
/* Measure the width of each image. */
var test = $(this).find('.scrolling img').width();
/* Find out how many images there are. */
var testimg = $(this).find('.scrolling img').length;
/* Do the maths. */
var final = (test* testimg)*1.2;
/* Apply the maths to the CSS. */
$(this).find('scrolling').width(final);
});
Здесь вы просматриваете все свои div с целевым классом и выполняете вычисления. В этом цикле вы можете просто использовать $(this)
чтобы указать текущий выбранный <div>
.
Ответ 4
Как насчет .each()
?
http://api.jquery.com/each/
Ответ 5
Так же, как мы ссылаемся на класс scrolling
$( ".scrolling" ).each( function(){
var img = $( "img", this );
$(this).width( img.width() * img.length * 1.2 )
})