2

簡単なことだと思います...2divのコンテンツを交換し、残りのアクションを各要素にバインドします。今私はこれを持っています:

<div class="From">
    //something here, doesnt matter
</div>

<div class="To">
    //something here, doesnt matter
</div>
....
function switchElems() {
    var from = $( ".From" );
    var to = $( ".To" );
    var fromHtml = from.html();
    var toHtml = to.html();
    from.html( toHtml );
    to.html( fromHtml );
}

ただし、コンテンツを切り替えるだけで、内部の要素に関連するすべてのアクションのバインドを解除します。アクションとは、追加のプラグインによって追加された、内部のコンテンツに含まれるロジック全体を意味します。たとえば、クラスのあるdiv内fromにはinput、jQuerygeocompleteプラグインがバインドされています。elemsを切り替えた後でも、その入力にジオコンプリート機能を持たせたいのですが、名前付きinputにする必要があります。divTo

どうすれば修正できますか?

4

3 に答える 3

4

イベント委任を使用して、各div内の要素にイベントをバインドします。そうすれば、のHTMLを変更してもdiv、イベントリスナーは機能します。

例えば:

$('#from').on('click', '.my-element', handler);  

この場合、#fromのコンテンツを更新すると、新しいmy-elementsが表示され、ハンドラーが作成されます。

またswitch、JavaScriptで再保存された単語であるため、functionという名前を付けないでくださいswitch

于 2013-01-26T19:17:47.917 に答える
0

一つには、あなたのクラスは"最後に欠けていました

HTML:

<div class="From">
    //something here, doesnt matter
</div>
<div class="To">
     //something here, doesnt matter
 </div>

Javascript:

$('class_or_id').change(function(){
     var from = $( ".From" );
     var to = $( ".To" );
     var fromHtml = from.html();
     var toHtml = to.html();
     from.html( toHtml );
     to.html( fromHtml );
});

また

$('class_or_id').click(function(){
     var from = $( ".From" );
     var to = $( ".To" );
     var fromHtml = from.html();
     var toHtml = to.html();
     from.html( toHtml );
     to.html( fromHtml );
});
于 2013-01-26T19:23:30.700 に答える
0

要素を保持したい場合は、html()すべてを文字列に変換するを使用せずに、代わりにネイティブ要素を移動します。

$('class_or_id').click(function(){
    var from = $(".From"),
        to = $(".To"),
        fromContents = from.contents(),
        toContents = to.contents();

    to.append(fromContents);
    from.append(toContents);
});
于 2013-01-26T21:07:17.857 に答える