Javascript 使用单击处理程序从textarea中删除部分字符串
我有一些javascript,当用户单击“添加到篮子”按钮时,它会将产品标题添加到文本区域 如果用户单击特定行的删除按钮,如何从文本区域删除该行 文本区域可能如下所示:Javascript 使用单击处理程序从textarea中删除部分字符串,javascript,jquery,html,replace,textarea,Javascript,Jquery,Html,Replace,Textarea,我有一些javascript,当用户单击“添加到篮子”按钮时,它会将产品标题添加到文本区域 如果用户单击特定行的删除按钮,如何从文本区域删除该行 文本区域可能如下所示: Product name 1 Product name 2 Product name 3 如果用户添加了3个产品 如果用户然后单击产品2上的“删除”,文本区域应该如下所示 Product name 1 Product name 3 我不太清楚如何实现这一点。将JavaScript更改为使用数组来存储字符串(并可能对其进行排序
Product name 1
Product name 2
Product name 3
如果用户添加了3个产品
如果用户然后单击产品2上的“删除”,文本区域应该如下所示
Product name 1
Product name 3
我不太清楚如何实现这一点。将JavaScript更改为使用数组来存储字符串(并可能对其进行排序),然后在输出列表之前修改列表可能会有好处。大概是这样的:
var items = [];
// on click for adding
items.push(productTitle); // Add item to end of array
$(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output
// on click for removing
var index = items.indexOf(productNameToFind); // Find an item in the array
if(index != -1)
items.splice(index, index); // Remove item at found index
$(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output
你可以这样做
$('#YourRemoveButton').on('click', function () {
var lines = $('#box').val().split(/\n/);
lines['YourLineIndex - 1 '] = "";
lines = lines.filter(function(v){return v!==''});
$("#box").val(lines.join("\n"));
});
您需要获取插入符号在
文本区域中的位置,并拆分内容,以查看当前行是否正是您要查找的值
在本例中,我使用了文本来删除作为示例:
$('#btn1')。单击(函数(){
//获得插入符号位置
cur=$('#ta').prop(“selectionStart”);
//保存textarea的值
str=$('#ta').val();
beforeCursor=str.substr(0,cur);
afterCursor=str.substr(cur);
splitted_before=beforeCursor.split(“\n”)
splitted\u after=afterCursor.split(“\n”)
lastline_before=拆分的_before.pop();
firstline_after=splitted_after.shift();
fullline=前最后一行+后第一行;
如果(全文==“要删除的文本”){
new_str=splitted_在.join之前(“\n”)+“\n”+splitted_在.join之后(“\n”)
$('ta').val(新街)
}
});代码>
删除
是否单击产品2上的“删除”?什么意思?移除什么?
var items = [];
// on click for adding
items.push(productTitle); // Add item to end of array
$(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output
// on click for removing
var index = items.indexOf(productNameToFind); // Find an item in the array
if(index != -1)
items.splice(index, index); // Remove item at found index
$(".tilvalg textarea").text(items.join('\n')); // Join items by new line and output
$('#YourRemoveButton').on('click', function () {
var lines = $('#box').val().split(/\n/);
lines['YourLineIndex - 1 '] = "";
lines = lines.filter(function(v){return v!==''});
$("#box").val(lines.join("\n"));
});