
本文旨在解决在PHP循环中嵌入大量重复JavaScript代码的问题。通过使用事件委托、类选择器和事件目标等技术,可以将JavaScript函数定义一次,并在循环生成的每个元素上复用,从而提高代码的可维护性和性能。本文将提供详细的步骤和示例代码,帮助你优化现有的代码结构,使其更加简洁高效。
优化循环内嵌JavaScript代码
在PHP循环中直接嵌入JavaScript代码,特别是当循环次数较多时,会导致大量的代码重复,降低代码的可读性和维护性。以下介绍一种更优雅的方法来解决这个问题,核心思想是将事件监听器绑定到父元素,并利用事件委托机制来处理子元素的事件。
1. 使用类选择器替代ID选择器
在循环中生成HTML元素时,避免使用唯一的ID,而是使用类选择器。这样可以方便地选中所有需要绑定事件的元素。
例如,将:
<input type="text" id="brand<?php echo $x;?>" class="brand-list" name="brand" value="<?php echo $item['brand']?>" onkeyup="editSave<?php echo $x;?>(), success()">
修改为:
<input type="text" class="brand-list item-brand" name="brand" value="<?php echo $item['brand']?>">
2. 利用事件委托绑定事件监听器
将事件监听器绑定到表格或其父元素上,而不是每个单独的元素。当子元素触发事件时,事件会冒泡到父元素,父元素根据事件目标(event.target)来判断是哪个子元素触发的事件,并执行相应的操作。
document.getElementById("mySEARCH").addEventListener("keyup", function(event) {
if (event.target && event.target.classList.contains("item-brand")) {
// 获取当前行的ID
const row = event.target.closest("tr");
const itemId = row.id.replace("line", "");
// 获取当前输入框的值
const brand = event.target.value;
// 执行保存操作
editSave(itemId, brand);
}
});
在这个例子中,我们监听了mySEARCH表格的keyup事件。当event.target(即触发事件的元素)包含item-brand类时,我们才执行相应的操作。event.target.closest("tr")用于查找最近的
3. 统一JavaScript函数定义
将JavaScript函数定义在循环外部,并修改函数以接受参数,从而实现对不同元素的处理。
在调试 Java 后端 API 故障时使用此技能,尤其适用于以下任务:分析日志、跨 Controller、Service 和 Mapper 层追踪请求、定位异常根因、检查 SQL 执行或参数流转,以及生成简洁的诊断结论与修复方案。
例如,将:
function editSave<?php echo $x;?>(){
var id = <?php echo $item['id']?>;
var brand = $("#brand<?php echo $x;?>").val();
var itemKind = $("#item-kind<?php echo $x;?>").val();
$.post("calculate.php", { save: id, brand: brand, itemkind: itemKind },
function(data) {
$('#edit-confirm').html(data);
});
}
修改为:
function editSave(itemId, brand, itemKind) {
var id = itemId;
var brand = brand;
var itemKind = itemKind;
$.post("calculate.php", { save: id, brand: brand, itemkind: itemKind },
function(data) {
$('#edit-confirm').html(data);
});
}
4. 修改PHP代码
修改PHP代码,移除循环中嵌入的JavaScript代码,并添加必要的类和数据属性。
<?php if(isset($_COOKIE['shoppinglist'])){
$list = $_COOKIE['shoppinglist'];
$stmt = $pdo->prepare("SELECT * FROM `$list`");
$stmt->execute();
$x = 0;
foreach($stmt as $item)
{ $x++;?>
<tr id="line<?php echo $x;?>" style="opacity: 1.0;" data-item-id="<?php echo $item['id']; ?>">
<td><button class="btn-hide-row activ" data-line="<?php echo $x;?>">@@##@@</button></td>
<form action="calculate.php" method="post">
<td class="pcs-unit-list"><?php echo $item['pieces']." ".$item['unit']?></td>
<td name="item" class="shop-list-item" id="item"><?php echo $item['item']?></td>
<td class="brand-list"><input type="text" class="brand-list item-brand" name="brand" value="<?php echo $item['brand']?>"></td>
<td class="kind-list"><select class="shoppinglist-kind item-kind" name="item-kind"><option value=""></option>
<option value="Gemüse" if echo>>Gemüse</option>
<option value="Obst" if echo>>Obst</option>
<option value="Fleisch" if echo>>Fleisch</option>
<option value="Fisch" if echo>>Fisch</option>
<option value="Getreideprod." if echo>>Getreideprod.</option>
<option value="Milchprod." if echo>>Milchprod.</option>
<option value="Gewürze" if echo>>Gewürze</option>
<option value="Knabbern" if echo>>Knabbern</option>
<option value="Getränke" if echo>>Getränke</option>
<option value="Kräuter" if echo>>Kräuter</option>
<option value="Hygiene" if echo>>Hygiene</option>
<option value="Putzen" if echo>>Putzen</option>
<option value="Haustier" if echo>>Haustiere</option>
<option value="Sonstiges" if echo>>Sonstiges</option></select></td>
<td class="list-button"><button class="btn-list" name="delete" value="<?php echo $item['id']?>">@@##@@</button></td>
</form>
</tr><?php }
}else {
/******************************************************************************** shopping list end****/
?><tr>
<td></td>
<td></td>
<td>Keine Items vorhanden</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr><?php }
?>
5. 完整的JavaScript代码示例
document.addEventListener("DOMContentLoaded", function() {
const table = document.getElementById("mySEARCH");
// 事件委托:品牌修改
table.addEventListener("keyup", function(event) {
if (event.target && event.target.classList.contains("item-brand")) {
const row = event.target.closest("tr");
const itemId = row.dataset.itemId; // 使用 data-item-id
const brand = event.target.value;
const itemKind = row.querySelector(".item-kind").value; // 获取 itemKind
editSave(itemId, brand, itemKind);
}
});
// 事件委托:种类修改
table.addEventListener("change", function(event) {
if (event.target && event.target.classList.contains("item-kind")) {
const row = event.target.closest("tr");
const itemId = row.dataset.itemId; // 使用 data-item-id
const brand = row.querySelector(".item-brand").value; // 获取 brand
const itemKind = event.target.value;
editSave(itemId, brand, itemKind);
}
});
// 事件委托:隐藏/显示行
table.addEventListener("click", function(event) {
if (event.target && event.target.classList.contains("activ")) {
const row = event.target.closest("tr");
const itemId = row.dataset.itemId;
const line = row;
const brand = row.querySelector(".item-brand");
const itemKind = row.querySelector(".item-kind");
const btnLocked = row.querySelector(".btn-list");
const btnImage = row.querySelector(".visibility");
if (line.style.opacity === "1") {
line.style.opacity = "0.1";
brand.setAttribute("readonly", "");
itemKind.setAttribute("disabled", "");
btnLocked.setAttribute("disabled", "");
btnImage.setAttribute("src", "images/icon-visible.png");
} else {
line.style.opacity = "1";
brand.removeAttribute("readonly");
itemKind.removeAttribute("disabled");
btnLocked.removeAttribute("disabled");
btnImage.setAttribute("src", "images/icon-invisible.png");
}
}
});
function editSave(itemId, brand, itemKind) {
$.post("calculate.php", { save: itemId, brand: brand, itemkind: itemKind }, function(data) {
$('#edit-confirm').html(data);
});
}
});
注意事项:
- 确保在DOM加载完成后绑定事件监听器,可以使用document.addEventListener("DOMContentLoaded", function() { ... });。
- 使用data-*属性来存储每个元素的ID,例如
,然后在JavaScript中使用element.dataset.itemId来访问。 - 根据实际情况调整选择器和事件类型。
总结:
通过使用事件委托、类选择器和统一的JavaScript函数,可以有效地减少PHP循环中嵌入的重复JavaScript代码,提高代码的可维护性和性能。这种方法使得代码结构更加清晰,易于理解和修改。

php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










