所以我正在做这个学校的东西,我正在尝试获取循环复选框的x和y坐标,当它们被选中并在各自的输入框中显示X和Y坐标时,我需要帮助,因为在此我真的不知道自己在做什么。
html.twig。
{% set cells = 10 %}
<div class="large-12">
<div class="large-6 columns">
<h6>Your Board</h6>
<table id="yours" class="ocean">
{% for i in 1..cells %}
<tr class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
{% if cell.hit == "hit" %}
hit
{% else %}
{{cell.class}}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" value="{{j}}"/>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<div class="large-12">
<div class="large-3 columns">
Y:<input type="text"/>
</div>
<div class="large-3 columns">
x:<input type="text"/>
</div>
<div class="large-3 columns">
<select>
<option>select</option>
<option>hit</option>
<option>miss</option>
</select>
</div>
<div class="large-3 columns">
<button>Initiate</button>
</div>
</div>
</div>
<script>
$('.chooser').click(function(){
$(this).removeClass('invisible');
var innerCheck = $(this).find('input[type=checkbox]')
innerCheck.prop('checked', true);
});
</script>
答案 0 :(得分:1)
$(function() {
$('.pos-input').on('click', function() {
if ($(this).is(':checked')) alert( $(this).data('x')+':'+ $(this).data('y') );
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
{% set cells = 10 %}
....
{% for i in 1..cells %}
<tr id="{{i}}" class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv chooser invisible
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
hit
{% else %}
no-ship
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" data-x="{{ j }}" data-y="{{ i }}" />
</td>
{% endfor %}
</tr>
{% endfor %}
&#13;
答案 1 :(得分:0)
更有效的实施方法是使用.on
来提高性能
使用.on
只有一个事件监听器处理DOM中每个输入框(带有类pos-input
)的任何点击,而不是处理事件监听器。
$(function() {
$('table').on('click', '.pos-input', function(e){
var targ = $(e.target);
if(targ.is(":checked")){
alert(targ.x + ", " + targ.dataset.y);
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
{% set cells = 10 %}
....
{% for i in 1..cells %}
<tr id="{{i}}" class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv chooser invisible
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
hit
{% else %}
no-ship
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" data-x="{{ j }}" data-y="{{ i }}" />
</td>
{% endfor %}
</tr>
{% endfor %}