简体   繁体   English

关联数组作为jQuery中的选择器和值

[英]associative arrays as selectors and values in jquery

Is it possible to implement associative arrays as Selectors and Values. 是否可以将关联数组实现为选择器和值。

I have an array 我有一个数组

   var obj = { surgeon:1, asstSurgeon:2, anesthe:3, nurse:4, scrub:5,....... };

I am able to implement like this. 我能够这样实现。

$("#surgeon").click(function(){
   $("$hiddenvariable").val(1);
});

$("#asstSurgeon").click(function(){
  $("$hiddenvariable").val(2);
});

................,

Can anyone help me how can i reduce the code. 谁能帮我减少代码。

Is there any other way to implement this. 还有其他实现方法。

with jQuery $.each 与jQuery $.each

$.each (obj, function(key, value) {
    $("#" + key).click(function(){
       $("$hiddenvariable").val(value);
    });
 });

or Using for..in and .on . 或使用for..in.on (Above method is better than below) (以上方法优于以下方法)

for (var i in obj) {
   $("#" + i).on('click', {i: obj[i]}, function(e){
       $("$hiddenvariable").val(e.data.i);
   });
}

How about this? 这个怎么样?

$.each(obj, function(type, i) {
    $('#' + type).click(function() { $('#hiddenvariable').val(i); });
});

Write a closure function in javascript, associate button ids with your closure variables and a common selector class 用javascript编写一个闭包函数,将按钮ID与您的闭包变量和一个公共选择器类相关联

then use jquery 然后使用jQuery

$(".selector").click(function(e){
    $("#hiddenfield").val(Closure.object[e.id]);
});

closure... 关闭...

function Closure() = {}
Closure.object = {
    surgeon:1, asstSurgeon:2, anesthe:3, nurse:4, scrub:5
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM