简体   繁体   English

当 ID 包含方括号时,jQuery 选择器失败

[英]jQuery selector fails when ID contains square brackets

I have a php script that creates a number of inputs whose ID's are in an array.我有一个 php 脚本,它创建了许多 ID 位于数组中的输入。 I am trying to check the value in the clicked one but it fails due to the selector being an array, I think.我正在尝试检查单击的值,但由于选择器是一个数组而失败,我认为。 The code I'm using is below.我正在使用的代码如下。 The amt var is undefined. amt 变量未定义。 If I change the code to not use arrays, it works.如果我将代码更改为不使用 arrays,它可以工作。 Is there a way to access an ID that is an array element?有没有办法访问作为数组元素的 ID? Here is my jsfiddle .这是我的jsfiddle

 $(".map-price").keyup(function(event) { var id = event.target.id; var amt = $("#" + id).val(); console.log(id + ' ' + amt); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input type="input" name="map_price[1]" id="products_map_price[1]" class="map-price"> </div> <div> <input type="input" name="map_price[2]" id="products_map_price[2]" class="map-price"> </div>

You can pass the whole element into jquery:您可以将整个元素传递给 jquery:

 $(".map-price").keyup(function(event) { var amt = $(event.target).val(); console.log(event.target.id + ' ' + amt); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input type="input" name="map_price[1]" id="products_map_price[1]" class="map-price"> </div> <div> <input type="input" name="map_price[2]" id="products_map_price[2]" class="map-price"> </div>

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

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