简体   繁体   English

如何让多个按钮在同一页面上触发一个js函数

[英]How To have multiple buttons trigger one js function on the same page

How would I be able to use 2 different buttons to render the same product purchase modal in the same if statement? 我如何能够使用2个不同的按钮在相同的if语句中呈现相同的产品购买模式?

I have a page where I only have one product but have 3 payment buttons (2 rendered in one case and 1 in another using an if/else statement). 我有一个页面,其中我只有一种产品,但是有3个付款按钮(在两种情况下使用if / else语句呈现2个,在另一种情况下呈现1个)。

The first button in the if section works and the one works in the else but the second button doesn't work in the if. if部分中的第一个按钮有效,而else部分中的一个有效,但是if部分中的第二个按钮无效。

I have tried using .getElementsByClassName('purch-btn') and changing the button classes respectively. 我尝试使用.getElementsByClassName('purch-btn')并分别更改按钮类。

I have also tried using .querySelectorAll('btn_buy, btn_buy_two') and assigning one of those ids to each of the buttons. 我也尝试过使用.querySelectorAll('btn_buy, btn_buy_two')并将这些ID之一分配给每个按钮。

Neither of these work. 这些都不起作用。

The Pack view : 打包视图

<% if @pack.category_id == "sample-pack" %>

  <div class="col-md-4">
    <div class="wellington top-drop prod-pod">
      <button class="btn btn-success btn-block" id="btn_buy" type="button">Purchase This Library</button>
    </div>
  </div>

  <div class="col-md-12">
    <button class="btn btn-success btn-block top-drop" id="btn_buy_two" type="button">Purchase This Library</button>
  </div>

<% else %>

  <div class="col-md-8">
    <div class="wellington top-drop">
      <button class="packview-addcart btn btn-lg btn-success" id="btn_buy" type="button">Buy!</button>
    </div>
  </div>

<% end %>
<%= render 'purchase_modal' %>

The Purchase modal: 购买模式:

<script>
  var handler = StripeCheckout.configure({
    key: '<%= Rails.configuration.stripe[:publishable_key] %>',
    token: function(token, arg) {
      document.getElementById("stripeToken").value = token.id;
      document.getElementById("stripeEmail").value = token.email;
      document.getElementById("chargeForm").submit();
    }
  });
  document.getElementById('btn-buy').addEventListener('click', function(e) {
    handler.open({
      zipCode: 'true',
      // image: '<%= @pack.art_link %>',
      name: '<%= @pack.title %>',
      description: 'Total: $<%= @pack.price %> USD',
      amount: document.getElementById("amount").value
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation:
  window.addEventListener('popstate', function() {
    handler.close();
  });
</script>

like this 像这样

document.querySelectorAll('#btn_buy, #btn_buy_two').forEach(function(btn) { btn.addEventListener('click', function(e) {
    handler.open(...[YOUR CODE]...);
    e.preventDefault();
  })
});

I ended up just having to use two purchase modals (one for each button). 我最终只需要使用两种购买模式(每个按钮一个)。

In the if statement, I simply added a render <%= render 'purchase_modal_two' %> for the button with id="btn_buy_two" since there was already one for the first button ( id="btn_buy" ) after it that will load for both the else and if . if语句中,我只是为具有id="btn_buy_two"的按钮添加了render <%= render 'purchase_modal_two' %> id="btn_buy_two" <%= render 'purchase_modal_two' %> ,因为在第一个按钮( id="btn_buy" )之后已经存在一个elseif

The only difference in both modals where here: 两种模态的唯一区别在于:

purchase_modal: purchase_modal:

document.getElementById('btn_buy').addEventListener('click', function(e) {

purchase_modal_two: purchase_modal_two:

document.getElementById('btn_buy_two').addEventListener('click', function(e) {

I am still open to actual answers to this question, as this is kind of a workaround and would love to know if it's possible to do this with only one <script> section! 我仍然对这个问题的实际答案持开放态度,因为这是一种解决方法,很想知道是否可以仅使用一个<script>部分来执行此操作!

One solution can be using document.querySelectorAll("#btn_buy, #btn_buy_two") This function will return an array containing the two elements you are looking for. 一种解决方案可以使用document.querySelectorAll("#btn_buy, #btn_buy_two")这个函数将返回一个包含您要查找的两个元素的数组。

Since you want them to do the same thing when they are clicked you need .forEach(function(button){}) that will iterate thorough them. 因为您希望他们在单击时做同样的事情,所以需要.forEach(function(button){})来遍历它们。

This function will return one by one the buttons, and store them in the variable " button ". 此函数将一个接一个地返回按钮,并将它们存储在变量“ button ”中。

You can now act on them as they were a single element: 您现在可以对它们进行操作,因为它们只是一个要素:

button.addEventListener('click', function(e) {
    handler.open({
        zipCode: 'true',
        // image: '<%= @pack.art_link %>',
        name: '<%= @pack.title %>',
        description: 'Total: $<%= @pack.price %> USD',
        amount: document.getElementById("amount").value
    });
    e.preventDefault();
});

I wrote a sample code snippet: 我写了一个示例代码片段:

 document.querySelectorAll('#btn1, #btn2').forEach(function(button) { button.addEventListener('click', function(e) { // ----- YOUR CODE ----- console.log("some action") }) }); 
 <button id="btn1">Button 1</button> <button id="btn2">Button 2</button> 

The two buttons perform the same action without having to write it twice. 这两个按钮执行相同的操作,而无需两次编写。

(I changed the code to make it more accessible to other users having the same issue) (我更改了代码,以使其他具有相同问题的用户可以更轻松地访问它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Vue.js:如何触发一个 function 在同一元素上有多个事件? - Vue.js: How can I trigger one function with multiple events on the same element? 如何在一个页面上为测验提供多个提交按钮 - How to have multiple submit buttons for a quiz on one page 如何在同一页面的多个按钮上打开一个Bootstrap模式? - How to open one Bootstrap modal on multiple buttons on the same page? 如何让多个按钮调用相同的JavaScript - How to have multiple buttons calling same JavaScript 用多个按钮触发相同的popbox - trigger the same popbox with multiple buttons 无论如何,当我在页面上有多个Like按钮时,是否会阻止多次加载相同的JS / CSS文件? - Is there anyway to prevent the same JS/CSS file from being loaded multiple times when I have multiple Like buttons on a page? 我在同一页面上有三个可供用户登录的地方,我如何才能在一个功能中同时使用所有三个按钮和三个表单来进行处理 - i have three places for users to log in, on the same page, how can i get all three buttons to work and three forms to process within one function 如何使用多个按钮触发相同的下拉/弹出窗口? - How to trigger the same drop-down/popover with multiple buttons? 如何在js的同一页面上创建多个实例function - how to create Multiple instances on the same page of js function 如何在同一页面中使多个阅读更多阅读更少按钮 - How to make multiple read more read less buttons in the same one page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM