0

我使用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>
4

2 回答 2

0

试着让它充满活力。利用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(); 
  });       
});
于 2019-10-12T14:17:33.163 回答
0

增量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>

于 2019-10-12T14:30:56.680 回答