gpt4 book ai didi

javascript - jquery的每个函数都不起作用

转载 作者:行者123 更新时间:2023-12-03 08:49:45 24 4
gpt4 key购买 nike

嗨,我有这个 html 代码

<html>

<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/sunny/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<link href="stile.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">

</head>

<body>
<form action="">
<div>
<div style="float:left; margin-right:3%">XXX</div>
<div>
<input type="text" name="price" id="price" value="2">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>

<div>
<div style="float:left; margin-right:3%">YYY</div>
<div>
<input type="text" name="price" id="price" value="3">
</div>
<div style="float:left; margin-right:3%">
<input type="button" name="button" id="button" value="button">
</div>
</div>
<div id="total"></div>
<script src="js/mine.js"></script>

</form>
</body>

</html>

以及文件mine.js中的以下js代码

$("#button").each(function() {

var sum = 0;

$('#price').each(function() {
sum += Number($(this).val());
});

$('#total').text(sum);
});

我希望当我点击 div id 总计中的按钮时,它会给出字段价格的值。

因此,如果我单击第一个提交按钮,它会给出值 2,但如果我单击第二个按钮后,它不会求和 (2+3=5)

最佳答案

您应该使用class而不是id as jquery id 选择器 (#) 只返回一个元素

https://api.jquery.com/id-selector/

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle, jQuery performs an additional check before identifying the element as a match.

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

输入为

<input type="text" name="price" class="price" value="2">

<input type="button" name="button" class="button" value="button">

total为例您可以留下 ID,因为您将获得最终总数

所以你的代码会是这样的

$(".button").each(function() {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#total').text(sum);
});

更新:如果您使用此代码并单击第一个按钮,它将给出 2,然后单击另一个按钮,它将给出 5。您可以尝试禁用 click处理程序以防止再次添加。

$(document).on("click", ".button", function()
{
var sum = Number($('#total').text());
sum += Number($(this).closest("div").parent().find('.price').val());
$('#total').text(sum);
});

附录:每次按下按钮时增加的数量输入

<div>
<input type="text" name="quantity" class="quantity" value="0">
<input type="button" class="add-quantity">
</div>

$(document).on("click", ".add-quantity", function()
{
var input = $(this).closest("div").find(".quantity");
var currentVal = parseInt(input.val());
$(input).val(currentVal+1);
});

关于javascript - jquery的每个函数都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com