我想学习,我们可以在两个输入值中找到相同的数字吗? 例如:
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
JS
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
});
});
在.click
按钮上发生onClick事件时,然后在#multinumber
和#justonenumber
输入值中检查相同的数字,并在警报框中获得结果。
有没有办法做到这一点?有人可以在这里帮助我吗?
答案 0 :(得分:1)
这是你想要的吗?
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
if(multiple.indexOf(single) > -1) alert(single + " is found");
else alert(single + " isn't found");
});
});
答案 1 :(得分:1)
您可以获得第一个输入框的值。用,
分割,然后用.indexOf
检查其他输入。如果有,您可以将结果放入类似
$(".click").click(function(){
var x = $("#multinumber").val().split(",");
var y = $("#justonenumber").val();
if(x.indexOf(y) > 0){
alert(x.find(o=> o==y))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
答案 2 :(得分:1)
只需在您的indexOf
字符串上使用includes
或multiple
。 :)
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
根据评论中解释的问题,似乎要求确实涉及拆分数组。
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val().split(',');
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});