我想製作建議文本,用戶可以點擊並在標籤中創建一個句子。 如果我有像的句子「我的貓」,「我的狗是」,並「真棒」,用戶可以點擊他們,使這樣的句子:「我的狗是真棒」或「我的貓很棒「取決於用戶首先點擊哪個按鈕。但在按鈕中有更長的文字(如句子)。如何在輸入(textarea)字段中輸入多個值?
我還沒有代碼,因爲我不知道從哪裏開始。我只是有一個形象來證明我的想法:
我想製作建議文本,用戶可以點擊並在標籤中創建一個句子。 如果我有像的句子「我的貓」,「我的狗是」,並「真棒」,用戶可以點擊他們,使這樣的句子:「我的狗是真棒」或「我的貓很棒「取決於用戶首先點擊哪個按鈕。但在按鈕中有更長的文字(如句子)。如何在輸入(textarea)字段中輸入多個值?
我還沒有代碼,因爲我不知道從哪裏開始。我只是有一個形象來證明我的想法:
首先,工作的jsfiddle可以在這裏找到:http://jsfiddle.net/k3y9fa1v/
你可以做的按鈕是這樣的:
<button>My dog is </button>
<button>My cat is </button>
<button>awesome </button>
然後創建文本區域:
<textarea id='my-area'></textarea>
我們與這些交互,使用JQuery創建onClick事件處理程序:
// Create a listener that is fired when any button is clicked
$('button').click(function() {
// Get the text that is inside the button
var text = $(this).text();
// Get the current content of the textarea
var content = $('#my-area').val();
// Add the text to the textarea
$('#my-area').val(content + text);
});
附加代碼中插入鏈接
如果我們要插入鏈接,沒有把鏈接元素在按鈕本身,我們可以使用data屬性,它允許我們在元素上存儲任意的數據,讓jQuery和CSS與它交互。
對於初學者來說,我們將此按鈕添加到HTML代碼:
// The data-type will be used in our jQuery code to determine that this
// button should be interpreted as a link
// data-link-to provides the URL of the link
<button data-type='link' data-link-to='http://google.com'>google link</button>
注意數據 - 屬性可以有你想要的任何名稱(所以data-link-to
不是一個特別的名字,只是我做了) 。這個數據屬性非常有用。您的案例的更多示例可能是data-capital-first
(總是大寫第一個字母,data-capital-word
(總是大寫每個單詞)等......這些示例可能看起來很愚蠢,因爲您可以將字符串放在已具有正確大寫字符的按鈕中。但是如果你想讓你的代碼更復雜(檢測句子的開始,所以你可以添加一個大寫字母,這些可能是有用的)
你可以使用普通的CSS來定位這個元素,使用下面的選擇:
[data-type='link'] {
background-color:rgb(110, 177, 252);
}
關於選擇和它的瀏覽器兼容性的更多信息,請this link
我修改了上面的jQuery以使用我們添加的新按鈕。 jQuery有一個非常有用的內建函數.data()
,它可以讓我們獲得元素的特定數據屬性。
$('button').click(function() {
// Get the text that is inside the button
var text = $(this).text();
// Get the data-type attribute value
var type = $(this).data('type');
// Get the current content of the textarea
var content = $('#my-area').val();
// Check whether to add the text normally or add a link
if (type == 'link') {
// Retrieve the link address from the button and create the anchor text
var link_ref = $(this).data('link-to');
// Alter the text variable to be surrounded by tha anchor tag
// with its specified href
text = '<a href="' + link_ref + '">' + text + '</a>';
}
// Set the value of the textarea to the new value
$('#my-area').val(content + text);
});
這正是我所需要的!謝謝。如果我不能將某些文本鏈接起來怎麼辦?可能嗎? – purgeru 2015-02-06 14:56:50
你的意思是如果你需要文本鏈接到某個地方?這當然是可能的。如果這是你需要的,我會編輯我的答案並添加它。 – 2015-02-06 15:00:17
是的。將錨標籤添加到按鈕。但它將正常文本輸出到texarea。 – purgeru 2015-02-06 18:06:15