[英]Find and compare elements with matching attribute values in Jquery
How do I go on about selecting elements which has the same attribute values in jquery. 如何继续选择在jquery中具有相同属性值的元素。 And then comparing which of those 2 has a greater value.
然后比较这两个中哪个值更大。
Here is what I have so far. 这是我到目前为止所拥有的。 The problem that I'm having with this is that I don't really get any output if the first number in the pair is the larger one.
我遇到的问题是,如果该对中的第一个数字较大,我将不会得到任何输出。
<script>
$(function(){
var j = [];
$('.loo').each(function(index){
var grp = $(this).attr('data-x');
var num = $(this).val();
var id = $(this).attr('id');
var pair_val = pair_value(grp);
var pair_id = pair_identity(id);
console.log(get_max(num, pair_val, id, pair_id));
});
function get_max(num1, num2, id1, id2){
var decide = 0;
if(num1 > num2){
decide = id1;
}else{
decide = id2;
}
return decide;
}
function pair_value(conn){
var pair = $("input[data-x="+ conn +"]").val(); //my problem is here
return pair;
}
function pair_identity(conn){
var pair_id = $("input[data-x="+ conn +"]").attr('id'); //my problem is here
return pair_id;
}
});
</script>
Html: HTML:
<p>
<input type="text" id="e" name="e" class="loo" value="1" data-x="a">
</p>
<p>
<input type="text" id="f" name="f" class="loo" value="10" data-x="a">
</p>
<p>
<input type="text" id="g" name="g" class="loo" value="37" data-x="b">
</p>
<p>
<input type="text" id="h" name="h" class="loo" value="25" data-x="b">
</p>
<p>
<input type="text" id="i" name="i" class="loo" value="11" data-x="c">
</p>
<p>
<input type="text" id="j" name="j" class="loo" value="12" data-x="c">
</p>
var highest = new Array();
$('.loo').each(function(){
if(!highest[$(this).data('x')] || parseInt($(this).val()) > highest[$(this).data('x')] )
highest[$(this).data('x')] = parseInt($(this).val());
});
This will loop through all instances of .loo
and checks if there is no entry yet or if the current saved value is lower than the current elements value, in that case it will update the array entry. 这将遍历
.loo
所有实例,并检查是否还没有条目,或者当前保存的值是否小于当前元素的值,在这种情况下,它将更新数组条目。
This will leave you with an array containing all max values
for all possible values of data-x
这将留下一个数组包含所有最高
values
的所有可能的值data-x
EDIT 编辑
excuse me, some syntax errors were present. 对不起,存在一些语法错误。
EDIT 2 编辑2
shorter version 短版
The problem you're no doubt having is that you are comparing character strings (obtained with .val()
), not numbers. 毫无疑问,您遇到的问题是比较字符串(通过
.val()
获得)而不是数字。 This has a very different behviour - effectively deciding which one is alphabetically before another. 这具有截然不同的行为-有效地确定哪个字母按字母顺序排在另一个之前。
Change this line: 改变这一行:
if(num1 > num2){
to 至
if(parseInt(num1,10) > parseInt(num2,10)){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.