2012-09-12 32 views
0

我需要做兩個步驟:如何使用replaceWith jQuery?

1)單擊div時顯示InputBox。 2)當鼠標不在該輸入框中時顯示div。

步驟#2不起作用。

<html> 
    <title>a</title> 
    <head> 
    <script type="text/javascript" src="jquery-1.8.0.js"></script> 
    <script type="text/javascript"> 
     $(function() { 
      $('#field').click(function() { 
       $(this).replaceWith("<input type=\"text\" name=\"fname\" id=\"field\" value=\"" + $(this).text() + "\">"); 
      }); 

      $('#field').mouseout(function() { 
       $(this).replaceWith("<div id=\"field\">" + $(this).text() + "</div>"); 
      });  
     }); 
    </script> 
    </head> 
    <body> 
     <div id="field">hello there:)</div> 
    </body> 
    </html> 

謝謝:)

回答

2

當然這不會起作用,因爲您替換項目本身所以$(this)將不會引用任何內容。

,所以你必須調用鼠標移出結合創建新#field元素 後,也可以使用.on方法 http://api.jquery.com/on/

注意:您可以使用,而不是雙引號保存逃逸單引號;)

$('#field').click(function() { 
    $(this).replaceWith('<input id="field" type="text" value="' + $(this).text() + '>'); 

    // here you must call the mouse out binding 
    $('#field').mouseout(function() { 
     $(this).replaceWith('<div id="field">' + $(this).text() + '</div>'); 
    }); 

}); 
1

This will do what you want,您需要使用.on()方法,以便將事件綁定動態創建的元素。

.on()需要兩個或三個參數。第一個參數是事件,而第二個參數是要執行的函數或要綁定到的動態元素。如果您綁定到動態元素,則需要將該方法附加到容器元素。動態附加情況下的最後一個參數當然是要執行的功能。

<div id="container"> 
    <div id="field">hello there:)</div> 
</div>​ 
$(function() { 
    $('#container').on('click', '#field', function() { 
     $(this).replaceWith("<input type=\"text\" name=\"fname\" id=\"field\" value=\"" + $(this).text() + "\">"); 
    }); 

    $('#container').on('mouseout', '#field', function() { 
     $(this).replaceWith("<div id=\"field\">" + $(this).val() + "</div>"); 
    }); 

});​ 

UPDATE

$(function() { 
    $('#container').on('click', '#field', function() { 
     if (!$(this).is('input')) { 
      $(this).replaceWith("<input type=\"text\" name=\"fname\" id=\"field\" value=\"" + $(this).text() + "\">"); 
     } 
    }); 

    $('#container').on('mouseout', '#field', function() { 
     if ($(this).is('input')) { 
      if ($(this).val() != '') { 
       $(this).replaceWith("<div id=\"field\">" + $(this).val() + "</div>"); 
      } 
      else { 
       $(this).replaceWith("<div id=\"field\">hello there:)</div>"); 
      } 
     } 
    }); 

});​ 
+0

謝謝,爲什麼它不允許我在輸入框中手動更改文本?如果文字被改變,輸入框消失了? – eawedat

+0

@eawedat由於綁定的點擊。一會兒我解決它。 – Daedalus

+0

@eawedat作爲一個額外的例子,你可以寫這樣的事件http://jsfiddle.net/lollero/5xP9g/1/ – Joonas

2

你可以試試這個,讓不同的ID,當格說 「場」,並同時輸入說它 「txtfield」

$(function() { 
    $('#container').on('click', '#field', function() { 
     $(this).replaceWith("<input type=\"text\" name=\"fname\" id=\"txtfield\" value=\"" + $(this).text() + "\">"); 
    }); 

    $('#container').on('mouseout', '#txtfield', function() { 
     $(this).replaceWith("<div id=\"field\">" + $(this).val() + "</div>"); 
    }); 

}); 

檢查此DEMO

希望這會對你有所幫助。