简体   繁体   English

jQuery 选择器和 php 回路

[英]jQuery Selector and php loop

I have a PHP loop like this <?php foreach ($products as $product) {?> now inside this loop I will be creating some div .我有一个像这样的 PHP 循环<?php foreach ($products as $product) {?>现在在这个循环中我将创建一些div the number of div s created depends on number of products.创建的div的数量取决于产品的数量。 Also, I have a javascript function that creates a countdown.另外,我有一个 javascript function 可以创建倒计时。

Now I am trying to create a unique countdown in every div that gets created.现在我正在尝试在创建的每个 div 中创建一个独特的倒计时。 .ie unique countdown for every product. .ie 每个产品的独特倒计时。 here is the code that generates the coundown这是生成计数的代码

$(function(){$('.counter').countdown({startTime:"<?php echo $product['time']; ?>" });}); 

and this is what I have inside the php loop that creates the divs这就是我在创建 div 的 php 循环中所拥有的

<div class= 'counter' ></div>

now what this gives me is the same counter in all the divs.现在这给我的是所有 div 中的相同计数器。 I'm new to all this, I haven't slept in hours trying to learn and figure out what I'm doing wrong.我对这一切都很陌生,我已经好几个小时没有睡觉了,试图学习并找出我做错了什么。

EDIT:编辑:

So I still have not get what I want.所以我仍然没有得到我想要的。 $('.counter').each(function() { $(this).countdown(.... $('.counter').each(function() { $(this).countdown(....
produce the same counter for all the divs.为所有 div 生成相同的计数器。 and for some reason I get syntax error when I try to use $('#product-').countdown(... in order to create a unique selector.并且由于某种原因,当我尝试使用 $('#product-').countdown(... 以创建唯一选择器时出现语法错误。

This won't work as the selector .counter will find all elements with the class name counter .这不起作用,因为选择器.counter将找到所有具有 class 名称counter的元素。

Assuming that time varies for every product and that you have a unique identifier for every product, you could solve this by assigning an unique ID to every div-element, and use this as a means to trigger the countdown process:假设每个产品的时间都不同,并且您对每个产品都有一个唯一标识符,您可以通过为每个 div 元素分配一个唯一 ID 来解决这个问题,并将其用作触发倒计时过程的一种方法:

<div id="product-<?php echo $product['id']; ?>" class="counter"></div>

And the Javascript-code:和Javascript代码:

$('#product-<?php echo $product['id']; ?>').countdown({startTime: '...'});

I'd suggest a design pattern though where you don't have to generate javascript code like this.我建议一种设计模式,尽管您不必像这样生成 javascript 代码。

What you need is each()你需要的是 each()

$('.counter').each(function() { $(this).countdown({startTime:"" }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM