简体   繁体   English

jQuery attr()返回未定义

[英]jQuery attr() returns undefined

I'm using jquery function attr() to fetch a input element' custom attribute. 我正在使用jquery函数attr()来获取输入元素的自定义属性。 However this function returns undefined in Chrome. 但是,此函数在Chrome中返回undefined I tried to print this element and the result is: 我尝试打印此元素,结果是:

[prevObject: o.fn.init[1], context: document, selector: "input[name="money",uid="1"]", jquery: "2.1.0", constructor: function…]

Following are my js codes: 以下是我的js代码:

$('.panel').each(function(index, element) {
    var uid = $(this).attr('uid');
    console.log($(this));
    var moneyMinusBtn = $(this).find('.btn-money-minus')[0];
    var moneyPlusBtn = $(this).find('.btn-money-plus')[0];
    var moneyInput = $(this).find('input[name="money"]')[0];
    console.log($('input[name="money",uid="'+uid+'"]').attr('uid'));
}

HTML code: HTML代码:

 <input type="number" class="form-control" name="money" value="<?php echo $node['money'] ?>" uid="1" />

The problem is in the way you're chaining the attribute selectors. 问题在于您链接属性选择器的方式。 This will work: 这将起作用:

$('input[name="money"][uid="'+uid+'"]').attr('uid')

It might also be a good idea to use data-* attributes. 使用data- *属性也是一个好主意。

You need to check the rendered HTML to make sure that PHP wrote right values, but anyway, I think you cannot require two attributes in the way you showed: 您需要检查渲染的HTML以确保PHP编写正确的值,但是无论如何,我认为您不能以显示方式要求两个属性:

$('input[name="money",uid="'+uid+'"]')

Try changing it into: 尝试将其更改为:

$('input[name="money"][uid="'+uid+'"]')

Or even (might be faster selector, otherwise the same): 甚至(可能是更快的选择器,否则相同):

 $('input').filter('[name="money"][uid="'+uid+'"]') 

Note there is no space or separator of any kind between [name="money"] and [uid="'+uid+'"] . 注意[name="money"][uid="'+uid+'"]之间没有任何空格或分隔符。

See comments for performance discussion. 有关性能讨论,请参见评论。

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

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