简体   繁体   English

每个循环失败的jQuery插件?

[英]each loop fail in jquery plugin?

can anyone explain me what happen here?? 有人能解释一下这里发生的事情吗?

i have this html code: 我有这个HTML代码:

   <div class="calculadora">

      <div class="clear campos">
       <label>Amount</label>
       <input class="fi" id="amount" type="text" name="amount" value=""/>
      </div>

      <div class="clear campos">
       <label>Down Payment</label>
       <input class="fi" id="downPay" type="text" name="downPay" value=""/>
      </div>

      <div class="clear campos">
       <label>Years</label>
       <input class="fi" id="years" type="text" name="years" value=""/>
      </div>

      <div class="clear campos">
       <label>Rate</label>
       <input class="fi" id="rate" type="text" name="rate" value=""/>
      </div>

      <input id="cal" type="button" value="cacular"/>
      <div class="result"></div>
          </div>

And i'm making a jquery plugin, but i need to get all the attr('value') of each input, and i´m doing this way: 而且我正在制作一个jQuery插件,但是我需要获取每个输入的所有attr('value'),并且我这样做是:

this.each(function(){

        var obj = $(this),
        vacio = parseFloat( $('.fi', obj).attr('value'));

       // some code...

But what happens it's that only get the first value of the first input... why?? 但是会发生什么,那就是仅获得第一个输入的第一个值……为什么?

BUT!! 但!! if i make this way : 如果我这样做:

var s = $('.fi', obj).each(function(){
             alert ($(this).attr('value'))
            });

it workss!!! 它有效!!! Why?? 为什么?? this is good??? 这很好???

Tks in advance if anyone can explain to me. 如果有人可以向我解释,请提前告知。

.attr() returns the value of the specified attirbute from the first element in the collection is called upon. .attr()从调用集合中的第一个元素返回指定服装的值。

From the doc: 从文档中:

Get the value of an attribute for the first element in the set of matched elements. 获取匹配元素集中第一个元素的属性值。

When you make it the other way , you are extracting the value attribute data for each element in the matched set. 相反 ,您将为匹配集中的每个元素提取值属性数据。

One way to achieve what you're after could be done by using the .map() function, which returns a jquery array: 一种实现目标的方法可以通过使用.map()函数来完成,该函数返回一个jquery数组:

var vals = $('.fi', obj).map(function(){
    return this.value;
});

To transform it to a pure javascript array, you use vals.toArray(); 要将其转换为纯JavaScript数组,请使用vals.toArray();

Note: no need for jquery to get the value of an input because this in event handlers and in iteration on elements is the current DOMElement, so you can just do this.value . 注意:不需要jQuery来得到一个输入的值,因为this在事件处理程序,并在元素的迭代是当前一个DOMElement,所以你可以做this.value

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

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