php - Using Jquery .each function in a PHP foreach loop
问题描述
I am quite new to jquery, and i couldn't use .each function in a php foreach function. I am trying to do a quantity, unit price, total price table. I don't know how many table rows does user need, therefore used foreach function. Here is an example what i am trying to do:
my deneme2.php file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width= <script type="text/javascript">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>deneme5.js</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<div>
<input id="tst1"; type="text"; >
<input id="tst2"; type="text"; >
<input id="tst3"; type="text"; > <br><br>
</div>
<?php } ?>
<input id="asd"; type="submit"; value="hesapla">
</body>
</html>
And my deneme5.js file:
$(function(){
$("#asd").click(function(){
$("div").each(function(index){
var a=$("#tst1").val();
var b=$("#tst2").val();
var c= parseInt(a)*parseInt(b);
$("#tst3").val(c);
});
});
});
Can you help me? what am i doing wrong?
解决方案
您的代码中有许多语法错误。我稍微修改了一下。请把它和你的比较一下,看看你的错误在哪里。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- here i have added your javascript code directly. You can include it like that: <script src="deneme5.js"></script>-->
<script>
$(function(){
$("#asd").click(function() {
$(".row").each(function(index, element){
var a = $(element).find(".tst1").val();
var b = $(element).find(".tst2").val();
var c = parseInt(a) * parseInt(b);
$(element).find(".tst3").val(c);
});
});
});
</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<!-- in the following i have switched your ids into classes because ids have to be unique. Furthermore html attributes do not have to be separated by ';' -->
<div class="row">
<input class="tst1" type="text">
<input class="tst2" type="text">
<input class="tst3" type="text"><br><br>
</div>
<?php } ?>
<input id="asd" type="submit" value="hesapla">
</body>
</html>
这里所做的其中一件事是将 ID 的使用转换为类。ID 不能在页面上重复,因为这会导致 JavaScript 和 CSS 出现问题。
推荐阅读
- python - 如何递归地转换类实例的属性
- c# - 从 SQL Server 表中获取数据并更新为 XML 文件内容
- java - 我可以在 JpaRepository 的 saveAll 中混合更新和插入吗
- uml - 如何建模全局变量集
- html - 如何在 CSS 中使用多边形创建饼图
- uvm - item_collected_port 和 item_observed_port 之间的区别
- objective-c - Cocoa 编译失败
- angularjs - 未使用字段中的数据表搜索
- symfony - EasyAdmin 将用户显示为“未命名”,即使已登录
- docker - 如何在 docker 模块的 ansible 中修复“获取服务器 API 版本时出错”