如何根据单击的元素将不同的参数传递给函数? [英] How to pass different arguments to a function based on which element was clicked?

查看:49
本文介绍了如何根据单击的元素将不同的参数传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此并不陌生,所以如果我不太明确,请不要对我太苛刻.

I'm new to this, so if I'm not too explicit please don't be too harsh to me.

我制作了一个带有两个测试按钮的HTML文件.

I made an HTML file with two test buttons.

我在JavaScript中创建了一个名为 test()的函数,该函数包括对文件 test.php 的Ajax POST方法.

I created a function called test() in JavaScript which includes an Ajax POST method to the file test.php.

PHP文件将 1 0 写入名为 test.txt 的文本文件.

The PHP file writes 1 and 0 to a text file named test.txt.

所有这些仅需一个按钮.

All this for one button.

一切正常,但是我有这个问题:

Everything works fine, but I have this problem:

我希望在第二个按钮中调用我的 test()函数,该按钮具有不同的数据,例如 test2.php 和其他4个变量,例如 tag_test2 phptag_test2 On_test2 toggle_test2 .

I want my test() function to be called in the second button which has different data like test2.php and other 4 variables like tag_test2, phptag_test2 , On_test2, toggle_test2.

因此需要编写一个 test(testphp,tag,phptag,toggle,On)函数,以针对具有不同参数的这两个按钮调用它.

So would need to write a function test(testphp, tag, phptag, toggle, On) to call it for those two buttons with different parameters.

我已经尝试过此功能.

function test(testphp, tag, phptag, On, toggle) {

    if (toggle_test == 0) {
        toggle = 1;
        On = 1;
        tag = On;
        document.getElementById("result").innerHTML = On;

        $.ajax({
            type: "POST",
            url: testphp,
            data: {
                phptag: tag
            }
        });

        return test;
    }

    if (toggle == 1) {
        toggle = 0;
        On = 0;
    }
    tag = On;
    document.getElementById("result").innerHTML = On;

    $.ajax({
        type: "POST",
        url: testphp,
        data: {
            phptag: tag
        }
    });
}
}

然后在我的第一个按钮中调用它以查看它是否有效,但到目前为止没有成功.

And called it in my first button to see if it works, but no success so far.

我用 test('test.php',tag_test,phptag_test,On_test,toggle_test)替换了 test().

这是我的适用于第一个按钮的代码:

This is my code that works for the first button:

test.html

<html>
   <head>
      <title>Tests</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script type="text/javascript" src="jquery-3.4.1.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
   </head>
   <div>
   </div>
   <div class="Header2"> Cornel - Tests</div>
   <div class="space"></div>
   <body>
      <div class="container">
         <button type="button" class="btn btn-success" 
            onclick="test()">Test</button>
         <button type="button" class="btn btn-success">Test2</button>
         <div id="result"></div>
         <script>
var toggle_test = 0;
var On_test = 0;
var tag_test;

function test() {

    if (toggle_test == 0) {
        toggle_test = 1;
        On_test = 1;
        tag_test = On_test;
        document.getElementById("result").innerHTML = On_test;

        $.ajax({
            type: "POST",
            url: "test.php",
            data: {
                phptag_test: tag_test
            }
        });

        return test;
    }

    if (toggle_test == 1) {
        toggle_test = 0;
        On_test = 0;
    }
    tag_test = On_test;
    document.getElementById("result").innerHTML = On_test;

    $.ajax({
        type: "POST",
        url: "test.php",
        data: {
            phptag_test: tag_test
        }
    });
}
         </script>
         <style>
.btn-success {
    background-color: #2E64FE;
    border: none;
    color: white;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 20px;
}

.btn-success:hover {
    background-color: blue;
}

.btn-success:active:focus {
    background-color: blue;
}

.btn-success:focus {
    background-color: #2E64FE;
}

.btn-success:hover {
    background-color: blue;
}

.Header2 {
    padding: 50px;
    font-size: 50px;
    text-align: center;
    color: white;
    background-image: linear-gradient(#0033cc, #58FAF4);
    border: solid;
}

.space {
    padding: 25px;
}

.container {
    padding-left: 80px
}
         </style>
      </div>
   </body>

test.php

<?php
$tag_test = $_POST['phptag_test'];



$file=fopen('test.txt', 'w');
fwrite($file, $tag_test . "\n");
fclose($file);
?>

这将写入 test.txt 文件.

我的文件夹中也有一个 jquery-3.4.1.js 文件.

Also I have a jquery-3.4.1.js file in my folder.

推荐答案

以下是一些我认为可以解决您的主要问题的代码,即将动态值传递给函数.

Here is some code that I think resolves your primary issue, ie passing dynamic values to a function.

基本上,该方法是:

  • 为每个按钮添加唯一的 id 属性
  • 添加点击处理程序
  • 根据单击的按钮定义不同的功能参数

然后,您将可以通过条件处理传递给服务器端代码的值来处理您的不同方案.

You will then be able to handle your different scenarios via conditional handling of the values passed through to your server side code.

jsFiddle链接

注意:jsFiddle使用 mockjax 来模拟从服务器检索结果时的延迟,并将多个值记录到控制台,以便您可以更好地了解代码中发生的情况,但是您可以在实施时删除所有代码

note: the jsFiddle uses mockjax to emulate a delay when retrieving results from the server, and logs several values to the console so you can better understand what is happening in the code, but you can remove all that code when implementing

HTML

<!-- added unique id's to your buttons -->
<div class="container">
  <button id="button1" type="button" class="btn btn-success">Test1</button>
  <button id="button2" type="button" class="btn btn-success">Test2</button>

  <div id="result"></div>
</div>

JS

// added on click handler
$(document).on("click", "#button1, #button2", function() {

  // get reference to the instance of the button  
  var instance = $(this).attr("id");

  // sanity check  
  console.log("the instance is: " + instance);

  // create an object to store function parameters
  var parameters = {};

  // assign different values based on the instance  
  if (instance === "button1") {

    parameters.php_file = "my_file_1.php";
    parameters.tag = "tag 1";
    parameters.phptag = "php tag 1";
    parameters.is_toggled = true;
    parameters.is_on = false;

  } else if (instance === "button2") {

    parameters.php_file = "my_file_2.php";
    parameters.tag = "tag 2";
    parameters.phptag = "php tag 2";
    parameters.is_toggled = false;
    parameters.is_on = true;

  }

  // call the function
  my_function(parameters);

});


const my_function = (parameters) => {

  var php_file = parameters.php_file;

  $.ajax({
    url: `/path/to/your/file/${php_file}`,
    data: parameters, // send the parameters to your server side file
    type: "POST", 
    success: function(response) {

      // handle the response here  
      $("#result").text(response);

    }
  });

}

CSS

.btn-success {
  background-color: #2E64FE;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
}

.btn-success:hover {
  background-color: blue;
}

.btn-success:focus {
  background-color: #2E64FE;
}

.btn-success:active:focus {
  background-color: blue;
}

.Header2 {
  padding: 50px;
  font-size: 50px;
  text-align: center;
  color: white;
  background-image: linear-gradient(#0033cc, #58FAF4);
  border: solid;
}

.space {
  padding: 25px;
}

.container {
  padding-left: 80px;
}

#instance {
  font-size: 18px;
  color: black;
  font-weight: bold;
  margin-top: 20px;
  font-family: arial;
}

#result {
  font-size: 38px;
  color: deeppink;
  font-weight: bold;
  margin-top: 20px;
  font-family: arial;
}

这篇关于如何根据单击的元素将不同的参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆