我有多个带有属性name="user[]"
单击某个特定输入的按钮时,我需要找出点击了user
的索引。
我尝试了一些方法,例如.index()
,.attr('name")
,但我无法找到索引。
这怎么可能?
<div>
<input type="hidden" name="user[]"> <!-- index 0 -->
<button class="btn btn-primary">
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 1 -->
<button class="btn btn-primary">
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 2 -->
<button class="btn btn-primary">
</div>
...
可以通过单击按钮添加新div。 这用于用户邀请表单,因此没有ID。
我需要这样的东西
$('button').on('click', function() {
var index = $(this).parent().children('input').getTheIndex();
// where the index is defined by the use of []
});
答案 0 :(得分:1)
如果每个按钮都与特定的隐藏元素相关,则可以执行此操作:
var $users = $("input[type=hidden]");
var $buttons = $(".btn-primary");
$buttons.on("click", function(){
// Get the index of the button, since it will match the
// index of the input
alert("Button index was: " + $buttons.index(this));
// Get the index of the hidden element that comes just before the
// button that was clicked:
alert("Hidden index was: " + $users.index(this.previousElementSibling));
});
小提琴:https://jsfiddle.net/cvnwr89p/5/
顺便说一下,您需要关闭<button>
元素。
答案 1 :(得分:1)
jQuery的.index()
找到给定集合中元素的索引。
因此,要在name="user[]"
输入中进行搜索,您首先需要找到所有这些输入:
var index = $(':text[name="user[]"]')...;
然后,您可以确定其中当前输入的.index()
:
var index = ...index(currentInput);
示例:
$('button').on('click', function() {
var allUsers = $('[name="user[]"]');
var user = $(this).siblings('[name="user[]"]');
var index = allUsers.index(user.get(0)); // get the native DOM node for the search
console.log(index); // 0, 1, ...
console.log(user.get(0) === allUsers.get(index)); // true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="hidden" name="user[]"> <!-- index 0 -->
<button class="btn btn-primary">Test</button>
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 1 -->
<button class="btn btn-primary">Test</button>
</div>
<div>
<input type="hidden" name="user[]"> <!-- index 2 -->
<button class="btn btn-primary">Test</button>
</div>
答案 2 :(得分:0)
我认为您需要将该输入框的data
属性设置为类似data-user-id=42
的内容,以便您可以查找checked
框并获取其data
属性。如果您想要“所有表单元素中的索引”之类的东西,而不是像document.getElementById("form").elements
这样的东西,您可以在那里寻找输入......
答案 3 :(得分:0)
你可以这样做:
if (window.matchMedia("(min-width: 1000px)").matches) {
/* the viewport is at least 1000 pixels wide */
} else if (window.matchMedia("(max-width: 999px)").matches){
/* the viewport is less than 999 pixels wide */
} else if (window.matchMedia("(max-width: 500px)").matches){
/* the viewport is less than 500 pixels wide */
}