如何为多个系列的 id 编写单个 jquery 函数,用于它们的一系列依赖 id?



我用下面打印的while循环编写了下面的代码

<p>
<input id="txtBox<?php echo $a; ?>" type="text" value="1" style="display:none;" />
<span id="txtBoxValue<?php echo $a; ?>">1</span>
</p>

当我单击或选择范围时,我需要将其转换为文本字段,取消选择后它将再次返回到范围文本

对于这个任务,我编写了多个 jquery 函数,但我需要它是一个函数,这可能吗?

提前致谢

<script> 
$(function() {
$('#txtBoxValue1').on('click', function() {
$(this).hide(); 
$('#txtBox1').show(); 
});
$('#txtBox1').on('blur', function() {
var that = $(this);
$('#txtBoxValue1').text(that.val()).show(); 
that.hide(); 
});

$('#txtBoxValue2').on('click', function() {
$(this).hide(); 
$('#txtBox2').show(); 
});
$('#txtBox2').on('blur', function() {
var that = $(this);
$('#txtBoxValue2').text(that.val()).show(); 
that.hide(); 
});
});
</script>

尝试使其动态化。 使用class="textboxevent" data-id="<?php echo $a; ?>"

<p>
<input class="textboxevent" id="txtBox<?php echo $a; ?>" data-id="<?php echo $a; ?>" type="text" value="1" style="display:none;" />    
<span class="txtBoxValue<?php echo $a; ?>">1</span>
</p>
$(function() {    
$('.textboxevent').on('click', function() {
var id = $(this).data('id'); 
$('#txtBox' + id).show(); 
});
$('.textboxevent').on('blur', function() {
var that = $(this);
var id = $(this).data('id');
$('#txtBoxValue' + id).text(that.val()).show(); 
that.hide(); 
});       
});

增量id属性是一种反模式,主要是因为它们会导致不必要的冗长JS逻辑。

更好的解决方案是在具有相同行为的元素上使用公共类,然后使用 DOM 遍历将元素与周围的元素相关联。试试这个:

jQuery(function($) {
$('.txtBoxValue').on('click', function() {
$(this).hide().prev('input.txtBox').show();
});
$('.txtBox').on('blur', function() {
var $that = $(this).hide();
$that.next('.txtBoxValue').text($that.val()).show();
});
});
.txtBox {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<input class="txtBox" type="text" value="1" />
<span class="txtBoxValue">1</span>
</p>
<p>
<input class="txtBox" type="text" value="2" />
<span class="txtBoxValue">2</span>
</p>
<p>
<input class="txtBox" type="text" value="3" />
<span class="txtBoxValue">3</span>
</p>

最新更新