【发布时间】:2021-07-23 00:35:03
【问题描述】:
我有一个 php/html 代码,用于迭代服务。我通过js创建模态表单,但是js代码仅在foreach(php)迭代的第一个元素上触发。
如何让 js 处理数组的每个元素?
php/html
<div class="cards">
<? foreach($catalog_product as $key => $catalog_product_value): ?>
<div class="card">
<div class="card__side card__side--front card__side--front-1">
<div class="header">
<h3><?=$catalog_product_value['name']?></h3>
</div>
<p class="btn-pink">Подробнее</p>
</div>
<div class="card__side card__side--back card__side--back-1">
<h3><?=$catalog_product_value['header']?></h3>
<p class="flip-text"><?=$catalog_product_value['title']?></p>
<?=$catalog_product_value['content']?>
<button
id="buy_product_form"
data-item="product"
data-item_id="<?=$catalog_product_value['product_id']?>"
data-id="card_<?=($key + 1)?>"
data-title="<?=htmlspecialchars($catalog_product_value['header'])?>"
<? if (!empty($catalog_product_value['options'])): ?>
data-options="<?=htmlspecialchars(json_encode($catalog_product_value['options']), ENT_QUOTES, 'UTF-8')?>"
<? else: ?>
data-price="<?=preg_replace('/[^0-9.]+/', '', $catalog_product_value['price'])?>"
<? endif; ?>
class="pop_maker">
<?=$catalog_product_value['price']?>
</button>
</div>
</div>
<? endforeach;?>
</div>
js代码
window.onload = function(){
button = document.getElementById('buy_product_form');
var atr = button.getAttribute('data-title');
var id = button.getAttribute('data-id');
var options = button.getAttribute('data-options');
var price = button.getAttribute('data-price');
var item_id = button.getAttribute('data-item_id');
var item = button.getAttribute('data-item');
button.id = id;
var _form = document.createElement('form');
.....
};
【问题讨论】:
-
id属性在文档中必须是唯一的。使它们独一无二或使用类。 -
ID 应该是唯一的,并且您正在复制 ID
buy_product_form。您应该为每个按钮创建特定的 ID,或者使用一个类来加载所有按钮。
标签: javascript php jquery foreach iteration