【问题标题】:How can I change span text based on the button clicked?如何根据单击的按钮更改跨度文本?
【发布时间】:2020-02-09 18:19:28
【问题描述】:

我想在用户点击后更改 html 页面上显示的数量。有 2 个按钮,单击每个按钮后,它应该将它们定向到一个新的 html,并且数量应该相应地改变。我知道这不是真正的方法,但我不确定我还能怎么做。目前,我只能追加所有金额。

<button onclick="myFunction1()" type="submit" id="one">BUY</button>
<button onclick="myFunction2()" type="submit" id="two">BUY</button>
function myFunction1() {
    window.location='pay.html';
};

function myFunction2() {
    window.location = 'pay.html';
};
 <span class="title" id="total"></span>
 <span class="title" id="total2"></span>
(function () {
    "use strict";

    $().ready(function () {

    })
    myFunction1()

    function myFunction1() {
        var totalamt = '$100';
        $('#total').html("<span style='float:right'>" + "Total:" + 
        totalamt + "</span>");
    }

})();

(function () {
    "use strict";

    $().ready(function () {

    })
    myFunction2()

    function myFunction2() {
        var totalamt2 = '$300';
        $('#total2').html("<span>" + "Total:" + totalamt2 + 
        "</span>");
    }
})();

想要达到的结果:e.g.通过单击第一个按钮,将用户重定向到 pay.html 并显示 $100。通过单击第二个按钮,重定向到相同的 html(pay.html),显示 $300。请帮忙,非常感谢。

【问题讨论】:

  • 如果您不在实际应用程序中使用它,您可以在单击按钮时将值保存到本地存储,然后在新的 html 页面中显示它Save data to local storage 但如果您在实际应用程序中使用它应用程序你必须使用后端像 php , nodejs ...

标签: javascript jquery html button onclick


【解决方案1】:

pay.html 发送GET 请求,带参数:

window.location='pay.html?amount=100';

通过JS访问参数:

var url= new URL(document.location).searchParams;
var amount=url.get("amount");
var totalamt = '$'+ amount;
$('#total').html("<span style='float:right'>" + "Total:" + totalamt + "</span>");

你的html.html

<button onclick="myFunction1()" type="submit" id="one">BUY</button>
<button onclick="myFunction2()" type="submit" id="two">BUY</button>
function myFunction1() {
    window.location='pay.html?amount=100';
};

function myFunction2() {
    window.location = 'pay.html?amount=300';
};

pay.html

 <span class="title" id="total"></span>
var url = new URL(document.location).searchParams;//Getting search params
var amount = url.get("amount"); //Getting value of amount from parameters
var totalamt = '$'+ amount;
$('#total').html("<span style='float:right'>" + "Total:" + totalamt + "</span>");

这在没有 Real 应用程序的情况下也可以工作。

【讨论】:

    【解决方案2】:

    您可以将 id 设置为 span,然后将文本设置为 300 或 100

     <span id="price">$100</span>
       <scrit>
       document.getElementById("price").innerHTML = "$300";  
    </script>
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多