我无法让价格自动更新。
制作独特的id;我使用的价格:
id="target_1_<?php echo $product['product_id']; ?>"
并且我使用的选择菜单:
id="select_<?php echo $product['product_id']; ?>"
这是html / php
<?php foreach ($products as $product) { ?>
<span id="target_1_<?php echo $product['product_id']; ?>"><?php echo $product['price']; ?></span>
<?php } ?>
<?php if ($product['options']) { ?>
<?php foreach ($product['options'] as $option) { ?>
<?php if ($option['type'] == 'select') { ?>
<select name="option[<?php echo $option['product_option_id']; ?>]" class="select_options" id="select_<?php echo $product['product_id']; ?>" onchange="getIt(this);">
<?php foreach ($option['option_value'] as $option_value) { ?>
<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
(<?php echo $option_value['price_prefix']; ?><span id="newPrice"><?php echo $option_value['price']; ?></span>)
<?php } ?>
</option>
<?php } ?>
</select>
<?php } ?>
........
<?php } ?>
然后对于onchange函数我使用:
function getIt(el) {
var a = el.options[el.selectedIndex].text;
var position1 = a.indexOf("(");
var position2 = a.indexOf(")");
var position1 = position1+2
var finalA = a.substring(position1, position2);
document.getElementById("target_1_<?php echo $product['product_id']; ?>").innerHTML = "$"+finalA;
}
alert(finalA)给出了我需要的值,我似乎无法将其重新带回DOM
答案 0 :(得分:1)
改变这两个: 在getIt函数中传递product_id
<select name="option[<?php echo $option['product_option_id']; ?>]" class="select_options" id="select_<?php echo $product['product_id']; ?>" onchange="getIt(this,<?php echo $product['product_id']; ?>);">
使用带有productid参数concanate的id而不是使用php
function getIt(el, productid) {
var a = el.options[el.selectedIndex].text;
var position1 = a.indexOf("(");
var position2 = a.indexOf(")");
var position1 = position1+2
var finalA = a.substring(position1, position2);
document.getElementById("target_1_"+productid).innerHTML = "$"+finalA;
}
答案 1 :(得分:0)
试试这个:
function getIt(el) {
var a = el.options[el.selectedIndex].text;
var position1 = a.indexOf("(");
var position2 = a.indexOf(")");
var position1 = position1+2; //BTW , Your forgot ; over here
var product_id = <?php echo $product['product_id']; ?>;
//You always can use: console.log(product_id);
//Then check your browser's console to see this variable value
//In this case , just View Source and make sure that instead of the php line there's a valid
// number (the product's id)
var finalA = a.substring(position1, position2);
document.getElementById("target_1_"+product_id).innerHTML = "$"+finalA;
}
答案 2 :(得分:0)
在选择标记
中为产品ID添加其他数据属性,例如data-product-id
<select name="option[<?php echo $option['product_option_id']; ?>]"
data-product-id = "target_1_<?php echo $product['product_id']; ?>"
class="select_options" id="select_<?php echo $product['product_id']; ?>"
onchange="getIt(this);">
在Javascript中
function getIt(e) {
//Your part
document.getElementById(e.getAttribute("data-product-id")).innerHTML = "$"+finalA;
}