Jquery 单击输入字段后显示/隐藏div元素的更好方法

Jquery 单击输入字段后显示/隐藏div元素的更好方法,jquery,html,Jquery,Html,我有两个这样的输入字段 <input type="text" class="span3" id name="name" > <input type="text" class="span3" id name="phone" > <div class="show-example1"> show content 1 </div> <div class="show-example2"> show content 2 &

我有两个这样的输入字段

<input type="text" class="span3" id name="name" >
<input type="text" class="span3" id name="phone" >

<div class="show-example1">
      show content 1
</div>
<div class="show-example2">
      show content 2
</div>

我的脚本运行良好,但我只想知道一种更好的方法来执行上述操作。

我认为您的示例非常简单。如果我是您,出于性能原因,我会缓存选择器:

var showExample1 = $('.show-example1');
var showExample2 = $('.show-example2');
然后在代码中相应地使用它们,使用快速id选择器而不是慢速输入/名称选择器:

$("#phone").bind("click", function(e){
   e.preventDefault();
   showExample1.hide();
   showExample2.show(400);
});
等等。您还可以将单击事件绑定到单个事件中,以最小化代码并具有更好的可读性:

$("#name, #phone").bind('click.toggle', function(e) {
  e.preventDefault();
  if ($(this).prop('id') == 'name') {
     showExample1.hide();
     showExample2.show(400);
  } else {
     showExample2.hide();
     showExample1.show(400);
  }
});
如果以后要解除绑定,单击绑定器('.toggle')上的名称空间会有所帮助

如果您想拥有真正枯燥的代码,可以尝试以下方法:

var togglers = {phone: 'show-example1', name: 'show-example2'};
$.each(togglers, function(toggler, toggled) {
   $('#' + toggler).on('focus', function(e) { // if you call focus, also selecting the input via keyboard will work
     e.preventDefault();
     $('.' + toggled).show(400).siblings().hide(); // hiding all the elements on the same DOM level instead of just one
   });
});
我建议使用.on('click',function(event){而不是bind.on.是一个解释这一点的页面


看起来您正在尝试创建。请查看该链接。

这是我的解决方案。简言之,我使用标记属性、
焦点和
模糊事件来处理此任务。
与其他方法相比,它的好处是,只需几行jQuery,就可以覆盖所有表单元素,而无需手动打开/关闭其他div,同时保持JS的低调

HTML

JS


.

这个脚本有什么问题?或者为什么你认为这样不好?@SunilChavan只需以10个输入字段为例,在这种情况下,我必须为每个输入添加10个事件,并且在每个事件中我必须隐藏9个div元素。这会增加脚本的长度,因此我认为可能还有其他方法可以做到这一点。
var togglers = {phone: 'show-example1', name: 'show-example2'};
$.each(togglers, function(toggler, toggled) {
   $('#' + toggler).on('focus', function(e) { // if you call focus, also selecting the input via keyboard will work
     e.preventDefault();
     $('.' + toggled).show(400).siblings().hide(); // hiding all the elements on the same DOM level instead of just one
   });
});
<form>
    Other information <textarea name="other_information" class="hintable" hint-class="show-example1"></textarea><br />
    Nationality <textarea name="nationality" class="hintable" hint-class="show-example2"></textarea><br />
    <div class="example show-example1">
        Example 1
    </div>
    <div class="example show-example2">
        Example 2
    </div>
</form>
.example
{
    display: none;
}​
$('.hintable').focus(function() {
   $('.example').hide();
   $("."+$(this).attr('hint-class')).show();
});

$('.hintable').blur(function() {
   $('.example').hide();
});