2009-07-01 86 views
1

我創建了一個javascript函數,它將採用隱藏跨度,將該跨度內的文本複製並將其插入到網站上的單個textarea標記中。我已經寫了一個JavaScript函數來做到這一點(好吧,只是點擊幾下),但我知道有一個更好的方法 - 任何想法?該行爲類似於Twitter的Retweet,但是在博客中使用部分帖子。哦,我也在頭上打電話給jquery。JQuery複製文本並粘貼到textarea中

<script type="text/javascript"> 
function repost_submit(postID) {  
    $("#repost-" + postID).click(function(){ 
     $("#cat_post_box").empty(); 
     var str = $("span#repost_msg-" + postID).text(); 
     $("#cat_post_box").text(str); 
    }); 
} 
</script> 
+0

哦,還有,postID會通過標記中的onclick傳遞 – Schoffelman 2009-07-01 21:43:02

回答

1
$("#repost-" + postID).click(function(){ 
    $("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element. 
    $("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be. 
}); 

,敷在$(文件)的一切。就緒(函數(){/ 這裏插入代碼 /}),因此它會綁定到$( 「#repost-」 +帖子ID)按鈕或者在DOM加載時鏈接。

2

基於對你的問題的評論,我假設你有這樣的事情在你的HTML:

<a href="#" onclick="repost_submit(5);">copy post</a> 

而且我還假設,因爲你正在傳遞一個帖子ID可以有每頁超過一頁。

jQuery的美麗之處在於,您可以在不使用內聯JavaScript事件的情況下爲元素集做很酷的事情。這些現在被認爲是不好的做法,因爲最好是將Javascript與演示代碼分開。

正確的方法,那麼,將是做這樣的事情:

<a href="#" id='copy-5' class='copy_link'>copy post</a> 

然後你就可以有更多的是類似於:

<a href="#" id='copy-5' class='copy_link'>copy post</a> 
<a href="#" id='copy-6' class='copy_link'>copy post</a> 
<a href="#" id='copy-7' class='copy_link'>copy post</a> 

最後,您可以編寫代碼jQuery做這樣的事情:

$(function() { // wait for the DOM to be ready 
    $('a.copy_link').click(function() { // whenever a copy link is clicked... 
     var id = this.id.split('-').pop(); // get the id of the post 
     var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup 
     $('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas) 
     return false; 
    }); 
}); 

這是最好的方式來做到這一點,即使只有一個職位在這一頁。代碼的部分問題在於,第一次單擊它時會綁定該函數,而在隨後的單擊操作中,它最終會被調用。你可以通過改變它來做一個快速而骯髒的修復,只需要在document.ready中。

0

當我點擊鏈接時,出現在#cat_post_box中的文本是「對象對象」,Paolo的示例出現問題。一旦我將「.text()」添加到該聲明的結尾,我就工作了。

var str = $('#repost_msg-' + id).text(); 

感謝你的例子保羅!