我有4个容器,我需要知道哪一个被点击,或者当他们按下"输入"专注于输入框时的键。
如何修改我的代码才能做到这一点?
HTML(此处仅显示2个容器):
<div id="boxes">
<div class="container e_type1" data-custom-data="e_type1">
<div class="header"><h2>E Type 1</h2></div>
<div class="image"></div>
<div class="footer">
<input type="text" name="item_level" value="1" class="item_level" min="1" step="1" required>
</div>
</div>
<div class="container e_type2" data-custom-data="e_type2">
<div class="header"><h2>E Type 2</h2></div>
<div class="image"></div>
<div class="footer">
<input type="text" name="item_level" value="1" class="item_level" min="1" step="1" required>
</div>
</div>
</div>
<div id="dialog" title="Progress">
<p>
<div id="progressbar">
<div class="progress-label"></div>
</div>
</p>
<div id="message"></div>
</div>
JS Snippet(完整代码可以在JSFiddle中找到)
// Image container was clicked.
// Get data and send first Ajax request.
$(".image").click(function () {
//console.log("Let's Start! Image container was clicked");
$("#dialog").dialog("open");
var e_type_var = $(".container").data("custom-data"),
item_level_var = $(this).$("#item_level").val();
alert(e_type_var + " was clicked");
forgeAjax(e_type_var, item_level_var, 'first_req', function (error) {
// By default, show Cancel button.
$("#dialog").dialog({
buttons: [{
text: "Close",
click: function () {
$(this).dialog("close");
}
}]
});
// Focus Cancel button
$('.ui-dialog button:eq(1)').focus();
// If there's no error returned, show Cancel and Button2 buttons.
if (!error) {
$("#dialog").dialog({
buttons: {
'Cancel': function () {
$(this).dialog('close');
},
'Button2': function () {
$("#message").html("");
startProgressBar(e_type_var, item_level_var);
}
}
});
// Focus Button2.
$('.ui-dialog button:eq(2)').focus();
}
});
});
编辑:感谢大家指出id="item_level"
。这是我的疏忽,并没有解释为什么代码不起作用。它已从问题中删除。
答案 0 :(得分:0)
你的JSFiddle有这个:
$('#item_level').keypress(function (e) {
// Enter was pressed while in the input box.
if (e.which == 13) {
// Send .image container click.
$('.image').click();
}
});
选择基于id
的元素。但是您的输入具有相同的id
字段,这些字段应该是唯一的:
<input type="text" name="item_level1" value="1" id="item_level" class="item_level" min="1" step="1" required>
和
<input type="text" name="item_level2" value="1" id="item_level" class="item_level" min="1" step="1" required>
因此,您可以添加另一个$('#item_level').keypress(function ...
或只是更改您的选择器以查找具有相同名称的类:
$('.item_level').keypress(function (e) {
// Enter was pressed while in the input box.
if (e.which == 13) {
// Send .image container click.
$('.image').click();
}
});
<小时/> 有关jQuery选择器的更多信息:http://www.w3schools.com/jquery/jquery_selectors.asp