首先,可以在这里找到一个工作的 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- 属性可以有任何你想要的名字(所以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);
});