2012-11-16 14 views
3

我有這樣的HTML的標記:的jQuery,前置數據

<div id="destination"> 

</div> 

<input id="test" type="text" /> 

<button id="clicker">Click me</button>​ 

這jQuery的片段

$(document).on('click', '#clicker', function(event){ 

    var newCat = $('#test').val(); 
    $(newCat).prepend("#destination"); 
     alert(newCat); 
});​ 

的警告文字確實是在該領域在輸入的文本,但文本不會以div #destination結尾。

看到這個的jsfiddle例如: http://jsfiddle.net/FaAY4/

+0

你爲什麼要委託的事件'document'? –

回答

3

必須這樣做:

$(document).on('click', '#clicker', function(event){ 

    var newCat = $('#test').val(); 
    $("#destination").prepend(newCat); 
     alert(newCat); 
     }); 
+0

謝謝!在我的原始文件(在我做jsfiddle之前)我用prependTo。無論如何,你的答案工作:) –

1

爲什麼想要到elemet添加到價值?

var newCat = $('#test').val(); 

上面這行會給你文本框的值。

$(newCat) 

不會對應任何元素。

1

我認爲你是交換源和目標即:

$(document).on('click', '#clicker', function(event){ 
    var newCat = $('#test').val(); 
    $('#destination').prepend(newCat); 
     alert(newCat); 
});​ 

Fiddle updated

2

您使用prepend()不正確。語法是:

$(targetElement).prepend(newContent); 

像這樣來使用你的具體的例子:

$("#destination").prepend(newCat);