0

このような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>

入力フィールド「名前」をクリックした後、div要素「show-example1」のみを表示したい

入力フィールド「電話」をクリックした後、div要素「show-example2」のみを表示します

このために、各入力フィールドに関連付けられた 2 つの div 要素を作成しました。

以下は、上記のアクションを実行するための私のスクリプトです

 $('.show-example1').hide();
  $('.show-example2').hide();

$("input[name='name']").bind("click", function(event){

            $('.show-example2').hide();
            $('.show-example1').show(400);
            return false;

        }); 

    $("input[name='phone']").bind("click", function(event){

            $('.show-example1').hide();
            $('.show-example2').show(400);
            return false;

        });

私のスクリプトは正常に動作していますが、上記のアクションを実行するためのより良い方法を知りたいだけです。

4

3 に答える 3

1

これが私の解決策です。要するに、タグ属性focusblurイベントを利用してこのタスクを処理します。他のものと比較して、それの利点は、JS の目立たないアプローチを維持しながら、他のすべての div のオン/オフを手動で切り替える必要なく、数行の jQuery ですべてのフォーム要素をカバーできることです。

HTML

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

CSS

.example
{
    display: none;
}​

JS

$('.hintable').focus(function() {
   $('.example').hide();
   $("."+$(this).attr('hint-class')).show();
});

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

</p>

フィドルリンク

于 2012-07-05T12:37:29.180 に答える
0

あなたの例はかなり簡単だと思います。私があなたなら、パフォーマンス上の理由からセレクターをキャッシュします。

var showExample1 = $('.show-example1');
var showExample2 = $('.show-example2');

そして、遅い入力/名前セレクターではなく高速な ID セレクターを使用して、コードでそれらを適切に使用します。

$("#phone").bind("click", function(e){
   e.preventDefault();
   showExample1.hide();
   showExample2.show(400);
});

等々。クリック イベントを 1 つのイベントにバインドして、コードを最小限に抑え、読みやすくすることもできます。

$("#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') の名前空間は、後でバインドを解除する場合に役立ちます。

本当にDRYコードが必要な場合は、次のようなものを試すことができます。

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
   });
});
于 2012-07-05T12:32:38.727 に答える
0

bind の代わりに .on('click', function(event){ を実行することをお勧めします。これについて少し説明しているページがあります

jQuery アコーディオンを作ろうとしているようです 。そのリンクをチェックしてください。

于 2012-07-05T12:32:52.163 に答える