我想制作建议文本,用户可以点击并在标签中创建一个句子。 如果我有像的句子“我的猫”,“我的狗是”,并“真棒”,用户可以点击他们,使这样的句子:“我的狗是真棒”或“我的猫很棒“取决于用户首先点击哪个按钮。但在按钮中有更长的文字(如句子)。如何在输入(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