【问题标题】:get one value two times with jquery使用 jquery 两次获得一个值
【发布时间】:2009-09-02 14:42:11
【问题描述】:

我在 jquery 中有这段代码:

    $("#order_btn").click(function(){
        var totalprice = $(".price_amount").text();
        $("#totalprice").val(totalprice);
    });

当我提交这个带有隐藏值的表单时,我会得到两次总价格值,如果它是 200000,我会得到 200000200000。为什么?

<input type="hidden" value="" name="totalprice" id="totalprice">
<input id="order_btn" type="submit" class="submit" name="submit" value="submit">

价格金额将在此处定义:

<span class="price_amount">75000</span>

我有两次这个 span 标签,但我都需要,有没有办法只得到一个值?

【问题讨论】:

  • 你确定你有一个类price_amount的元素吗?如果是这样,你为什么不使用id 而不是class
  • 是两个具有相同类名的元素!

标签: javascript jquery forms


【解决方案1】:

您很可能有多个“price_amount”类的跨度标签

尝试使用

var totalprice = $(".price_amount:first").text();

var totalprice = $(".price_amount:eq(0)").text();
// therefore you can access the second span tag like this
var totalprice = $(".price_amount:eq(1)").text();
// and so on...

如果这使它起作用,请检查您的代码是否有多余的 span 标签

编辑: 应该是现在

编辑 2: 如果您的 totalprice 变量应该是所有“price_amount”跨度的总和,请考虑以下内容:

var totalprice = 0;
$.each($('.price_amount'),
      function()
      {
        totalprice += parseInt($(this).text());
      });

【讨论】:

  • 这很奇怪,你应该能够得到你“price_amount”跨度标签的值,尝试使用 $(".price_amount").get()[0].text()跨度>
  • 应该是$(".price_amount:first").text()
【解决方案2】:

您确定您的页面上只有一个具有price_amount 类的元素吗?如果您在分配 totalprice 的值后设置断点(或警报),您会得到什么?

另外一件事 - 我不确定这是否重要,但我会将这段代码放在一个处理程序中,以便您的表单提交而不是点击。

【讨论】:

    【解决方案3】:

    因为您有两个 &lt;span&gt; 元素的类为“price_amount”。

    尤其是这一行

    var totalprice = $(".price_amount").text();
    

    当您从 jQuery 集合中调用 .text() 时,它将聚合所有选定节点的值并返回。

    因此,要么确保您只有一个带有该类名的跨度,要么使您的选择器更具体/更细化,以便您只检索所需的节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      相关资源
      最近更新 更多