如何在输入(textarea)字段中输入多个值?

时间:2015-02-06 07:33:49

标签: javascript jquery html input tags

我想制作建议的文字,用户可以点击并在标签中创建一个句子。 如果我的句子有"我的猫是" "我的狗是" "真棒& #34; ,用户可以点击它们并制作如下句子:"我的狗很棒" "我的猫很棒#34 ; 取决于用户首先点击的按钮。但是按钮中的文本较长(如句子)。

我还没有代码,因为我不知道从哪里开始。我只有一张图片来展示我的想法:

Exaple of inserting text

1 个答案:

答案 0 :(得分:1)

首先,可以在这里找到一个有效的jsFiddle:http://jsfiddle.net/k3y9fa1v/

您可以按下这样的按钮:

<button>My dog is </button>
<button>My cat is </button>
<button>awesome </button>

然后创建textarea:

<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);
});
相关问题