【问题标题】:remove part of string from textarea with click handler使用点击处理程序从 textarea 中删除部分字符串
【发布时间】:2016-08-01 18:46:29
【问题描述】:

当用户单击“添加到购物篮”按钮时,我有一些 javascript 将产品标题添加到文本区域。

<a href="#" class="add-button" data-id="@fieldset.Id" data-producttitle="@fieldset.GetValue("productItemTitle")">Tilføj</a>

还有 javascript

var productTitle = settings.productTitle;           
$(".tilvalg textarea").text($(".tilvalg textarea").text() + productTitle + "\n");

如果用户单击特定行的删除按钮,我如何从文本区域中删除该行?

文本区域可能如下所示:

Product name 1
Product name 2
Product name 3

如果用户添加了 3 个产品

如果用户随后点击产品 2 上的“删除”,则文本区域应如下所示

Product name 1
Product name 3

我不太确定如何做到这一点。

【问题讨论】:

  • 在产品 2 上点击“删除”?你的意思是?删除什么?

标签: javascript jquery html replace textarea


【解决方案1】:

将您的 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

【讨论】:

    【解决方案2】:

    你可以这样做

    $('#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"));
    
        });
    

    【讨论】:

      【解决方案3】:

      您需要获取textarea 中插入符号的位置并拆分内容以查看当前行是否正是您要查找的值。

      在本例中,我以文本TEXT TO REMOVE 为例:

      $('#btn1').click(function() {
        // Get caret position
        cur = $('#ta').prop("selectionStart");
        
        // Save the value of the textarea
        str = $('#ta').val();
        
        beforeCursor = str.substr(0, cur);
        afterCursor = str.substr(cur);
        
        splitted_before = beforeCursor.split("\n")
        splitted_after = afterCursor.split("\n")
        lastline_before = splitted_before.pop();
        firstline_after = splitted_after.shift();
        
        fullline = lastline_before + firstline_after;
        
        if (fullline == "TEXT TO REMOVE") {
          new_str = splitted_before.join("\n") + "\n" + splitted_after.join("\n")
          $('#ta').val(new_str)
        }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <textarea id="ta" style="width: 450px; height: 250px;"></textarea><br />
      <button id="btn1">Remove</button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-02
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        相关资源
        最近更新 更多