[英]How to input multiple values into input(textarea) field?
我想做一些建議的文字,用戶可以單擊並在標簽中創建一個句子。 如果我有“我的貓是” , “我的狗是”和“真棒”之類的句子,則用戶可以單擊它們,然后根據句子中的哪個按鈕制作“我的狗真棒”或“我的貓真棒”之類的句子。用戶首先點擊。 但是按鈕中的文字較長(例如句子)。
我還沒有代碼,因為我不知道從哪里開始。 我只有一張圖片來說明我的想法:
首先,可以在這里找到有效的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
attribute可以具有您想要的任何名稱(因此data-link-to
不是一個特殊的名稱,只是我自己編寫的)。 這個數據屬性真的很有用。 針對您的案例的更多示例可能是data-capital-first
(始終大寫首字母, data-capital-word
(總是大寫每個單詞)等)。這些示例可能看起來很愚蠢,因為您可以在按鈕,該按鈕已經具有正確的大寫字母。但是,如果您要為此設置代碼更復雜(檢測句子的開頭以便可以添加大寫字母,則這些按鈕可能會很有用)。
您可以通過以下選擇器使用普通CSS將此元素定位為目標:
[data-type='link'] {
background-color:rgb(110, 177, 252);
}
有關選擇器及其瀏覽器兼容性的更多信息,請參見此鏈接 。
我修改了上面的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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.