简体   繁体   English

jQuery keyup - 不可见的第二个输入

[英]jQuery keyup - not visible second input

HTML: HTML:

<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>
<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>

jQuery: jQuery的:

<script type="text/javascript">
    $(function() {
        $("#number").keyup(function () {
          var value = $(this).val()*5;
          $("#price").text(value);
        }).keyup();
    });
</script>

Price is only displayed at first. 价格仅在最初显示。 Why? 为什么?

How it is correct to make? 怎么做是正确的? Blocks can be endless. 块可以是无穷无尽的。

UPDATE: 更新:

Make: 使:

var id = 1;
$('.number').each(function() { 
    $(this).attr('id', 'id_' + id++); 
});

How it associate? 怎么联想? Blocks can be endless. 块可以是无穷无尽的。

Your code is searching for id = price where as your html has price as class. 您的代码正在搜索id = price ,因为您的html的价格是类。

Basically instead of 基本上不是

$("#price").text(value);

you should be using 你应该使用

$(".price").text(value);

# is used for id selector and . #用于id选择器和. is used for class selector 用于类选择器

Update: 更新:

As per edited Code: 根据编辑的代码:

In your html there are two div with the same id, whereas every element should have a unique id. 在你的html中有两个具有相同id的div,而每个元素都应该有一个唯一的id。 Please change id of the element to be unique may be price1, price2 and then use 请将要素的id更改为唯一可能是price1,price2然后再使用

jQuery('#price1').text(value) or jQuery('#price2').text(value) as per your case jQuery('#price1').text(value)jQuery('#price2').text(value)根据你的情况

I'd suggest using the following: 我建议使用以下内容:

$('input:text.number').keyup(
    function() {
        var v = parseFloat($(this).val()),
            s = v*5;
        $(this).next('.price').text(s);
    });​

JS Fiddle demo . JS小提琴演示

The jQuery, onkeyup , takes the current user-entered value of the input , parses it to make sure it's a number, and then updates the next sibling-element that matches the supplied selector ( .price ) of the text-input, with the calculated number. jQuery的, onkeyup ,采取的当前用户输入的值input ,对其进行解析,以确保它是一个号码,然后更新所提供的选择(相匹配的下一个同级元素.price文本输入),与计算数量。

The above uses corrected, and now-valid, HTML: 以上使用了经过修正且现在有效的HTML:

<div class="block">
    <input type="text" value="1" class="number" />
    <div class="price"></div>
</div>
<div class="block">
    <input type="text" value="1" class="number" />
    <div class="price"></div>
</div>​

References: 参考文献:

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

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