JQuery事件监听器通过名称和参数调用函数

时间:2018-02-12 19:15:14

标签: javascript jquery

我已经看到了与此类似的其他问题,但我似乎无法找到我正在寻找的答案。

有没有办法将参数传递给JQuery事件监听器中的命名函数?

例如,我知道我可以这样做

$('#myelement').on("change", function(){
  var value = $(this).val();   
  myFunction(value);
});

但有没有办法只将函数名称传递给事件监听器?

像这样的东西

$('#myelement').on("change", myFunction($(this).val()));

我认为说实话是直截了当的,但我似乎无法找到办法。

3 个答案:

答案 0 :(得分:2)

您可以使用jQuery .on()方法将参数传递给处理函数。

其格式为while True: print("Welcome to a Degrees Celsius to Kelvin converter.") ready = str(input("Do you want to start converting from Degrees Celsius to Kelvin? Y/N")) while ready.upper() = "Y": magicnumber = 273.15 choice = input("If you want to convert from Celsius to Kelvin type 'celsius' ,if you want to convert from Kelvin to Celsius type 'kelvin'") if choice == "celsius": celsius = input("Type the temperature in Degrees Celsius.") result = int(celsius) + magicnumber print("%s Degrees Celsius is %s Kelvin" %(celsius, result)) elif choice == "kelvin": kelvin = input("Type the temperature in Kelvin") result = int(kelvin) - magicnumber print("%s Kelvin is %s Degrees Celsius" %(kelvin, result)) ,其中.on( events [, selector ] [, data ], handler )是您需要传递的任何对象。稍后可以通过处理程序中的data属性访问它。

检查此示例。请注意,如果您只想访问event.data,则不需要任何参数:$(this).val()已绑定到目标元素,因此您可以在其中使用myFunction



$(this).val()

$("#i").on("change", null, "My parameter", myFunction);

function myFunction(event) {
   console.log("Parameter: " + event.data);
   console.log("$(this).val() = " + $(this).val());
}




答案 1 :(得分:0)

假设我理解你想要的东西,我用过的一个解决方法是引用数组中的函数,如下所示

list_of_functions = [function_1,function_2];

function function_1(){
  alert("function 1 running");
}
function function_2(){
  console.dir("function 2 running");  
}

function run_function(function_index){
  return list_of_functions[function_index]();
}

$("#function_select").on("change",function(){
  run_function(this.value);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="function_select">
  <option disabled selected>Please select a function</option>
  <option value="0">function 1</option>
  <option value="1">function 2</option>
</select>

答案 2 :(得分:0)

您可以使用jQuery“on”方法,然后调用click事件侦听器,最后但并非最不重要的是调用您创建的函数。

$('button').on('click', clicked);

function clicked() {
	var val = $('#one').val();
  $('.response').html('<p>Value is ' + val + '</p>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<input type="text" id="one">
<button>Click Me</button>

<p class="response"></p>

相关问题