简体   繁体   English

从隐藏的哈希在jQuery中创建关联数组

[英]Create an associative array in jquery from hidden hashes

I am trying to create an associative array from hidden hashes. 我试图从隐藏的哈希创建一个关联数组。 The jquery below calls to the specific hashes, but I would like to create this dynamically with one code. 下面的jquery调用特定的哈希,但是我想用一个代码动态创建它。

$(document).ready(function() {
     $("#tokens").tokenInput([
         {id: 1, name: "Darren Criss"},
         {id: 2, name: "Ann Arbor T-shirt Company"},
         {id: 3, name: "StarKid Product Store"},
     ]);
 });

I tried to do this: 我试图这样做:

 $(document).ready(function() {
     var variable = $("input[type='hidden'][class='stores']").val();
      $("#tokens").tokenInput(variable);
 });

but it doesnt work. 但它不起作用。

here are the hashes 这是哈希

  <input id="1" class="stores" type="hidden" value="Darren Criss" taxonomies_count="9"  
 name="1" disabled="disabled"></input>

 <input id="2" class="stores" type="hidden" value="Ann Arbor T-shirt Company" 
 taxonomies_count="46" name="2" disabled="disabled"></input>

 <input id="3" class="stores" type="hidden" value="StarKid Productions Store" 
 taxonomies_count="22" name="3" disabled="disabled"></input>

Your current code calls tokenInput , but only passes it a single string (the value of the first input element encountered in the DOM. Assuming that these hashes are present in the DOM when the document loads, 您当前的代码调用tokenInput ,但仅将其传递给单个字符串(DOM中遇到的第一个input元素的值。假设在document加载时DOM中存在这些哈希,

  var val = $("input[type='hidden'][class='stores']").val();
  $("#tokens").tokenInput(val);

is functionally equivalent to 在功能上等同于

$("#tokens").tokenInput("Darren Criss");

which does not match the kind of argument expected by tokenInput (see http://loopj.com/jquery-tokeninput/#installation--setup ) (You seem to have the right idea in your first code example). 这与tokenInput期望的参数类型不匹配(请参阅http://loopj.com/jquery-tokeninput/#installation--setup )(在第一个代码示例中您似乎有正确的主意)。 Why not iterate over a jQuery input selection, pushing new hash objects into a list, and, finally, call tokenInput, passing it the complete list: 为什么不遍历jQuery input选择,将新的哈希对象推入列表,最后调用tokenInput,将完整的列表传递给它:

$(document).ready(function() {
    var hashes = [];
    $('input.stores').each(function(i, elem) {
        hashes.push({
            'id': $(elem).attr('id'),
            'name': $(elem).val(),
        });
    });
    console.log(hashes);
    //$('#tokens').tokenInput(hashes);
});

EDIT: 编辑:

what is the i and the elem? i和elem是什么?

My approach is using jQuery's built-in iterator function each ( http://api.jquery.com/jQuery.each/ ). 我的方法是使用jQuery的内置迭代函数eachhttp://api.jquery.com/jQuery.each/ )。 This utility function allows programmers to easily iterate over existing collections, including objects, arrays, and jQuery selections. 该实用程序功能使程序员可以轻松地迭代现有集合,包括对象,数组和jQuery选择。 Here is the function's signature (for lack of a better term) as seen in jQuery's documentation: 这是函数的签名(由于缺少更好的用语),如jQuery文档所示:

jQuery.each( collection, callback(indexInArray, valueOfElement) ) jQuery.each(集合,回调(indexInArray,valueOfElement))

You can call each on any iterable JavaScript object (eg - foo.each(...); ), although it is more common to see a jQuery selection preceeding the call. 您可以在任何可迭代的JavaScript对象(例如foo.each(...); )上调用each对象,尽管在调用之前先看到jQuery选择更为常见。 each expects you to pass it a callback function that accepts two arguments: an index/key argument, and a value/item argument (as a side note, you also have access to this , an implicit argument referencing the value/item) inside of the body of the callback. each函数each希望您向其传递一个回调函数,该函数接受两个参数:索引/键参数和值/项目参数(作为一个副注,您还可以访问this ,它引用值/项目的隐式参数)回调的主体。

each will call this function once for each item in the collection, automatically passing it the appropriate index/key and value arguments for you, based on the current item in the iteration. each都会对集合中的每个项目调用一次此函数,并根据迭代中的当前项目自动为您传递适当的索引/键和值参数。 jQuery selections are iterable array-like objects: they behave like JavaScript arrays, and their 'items' can be referenced using numerical indexes (eg — Calling $('div')[0] or $('div').get(0) will return a reference to first DOM element matching the div selector, if a div is present on the page). jQuery选择是可迭代的类似于数组的对象:它们的行为类似于JavaScript数组,并且它们的“项目”可以使用数字索引来引用(例如,调用$('div')[0]$('div').get(0)将返回对与div选择器匹配的第一个DOM元素的引用(如果页面上存在div)。

When we iterate over a jQuery selection, the 'items' that we are iterating over are references to DOM elements. 当我们遍历jQuery选择时,所遍历的“项”是对DOM元素的引用。 In my example, when I call each on a jQuery selection and provide it with a callback function, i is given the value of the current DOM element's index within the selection, while elem references the actual element. 在我的例子,当我打电话each上一个jQuery选择,并为其提供一个回调函数, i给出的选择中的当前DOM元素的索引值,而elem引用的实际元素。 Oftentimes we want to call jQuery methods on these elements inside of the callback function. 通常,我们想在回调函数内部的这些元素上调用jQuery方法。 This requires us to wrap the element as a jQuery object ( $(elem) ), allowing us to manipulate the element using all of jQuery's functionality. 这要求我们元素包装为jQuery对象( $(elem) ),从而允许我们使用jQuery的所有功能来操纵元素。

Conventionally, calling each on a jQuery selection follows this form: 按照惯例,在jQuery选择上调用each遵循以下形式:

$('your selector here').each(function(i,elem) {
    var foo = $(elem); //Allows us to treat the DOM element as a jQuery object
    //Do stuff ... foo.val().attr().css().toggle();
});

Further reading on jQuery objects: 进一步阅读jQuery对象:

and what does console.log(hashes); 以及console.log(哈希);

I've simply included a console.log() to let you explore the hash list that is generated. 我只包含了console.log() ,让您浏览生成的哈希列表。 It is not necessary for calling tokenInput . 不需要调用tokenInput

What you gave as the source are not hashes but HTML input tags. 您提供的源代码不是哈希,而是HTML输入标签。 If you want to extract values from them, you can use jquery's attr function . 如果要从中提取值,可以使用jquery的attr函数

$(function(){
  var tokens = $('.stores').map(function(index, el) {
     var element = $(el)
     return {
       id: element.attr('id'),
       name: element.attr('value')
     }
  })
  $("#tokens").tokenInput(tokens);
});

I'm not sure what you are trying to do with the hashes once you have them, but that should get you started. 我不确定一旦拥有哈希后您将如何处理哈希,但这应该可以帮助您入门。

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

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