簡體   English   中英

jQuery在td內添加一個文本框,如果第二次在同一單元格內發生click事件,則阻止添加更多文本框

[英]jQuery add one text box inside a td and prevent adding more if click event occured second time inside the same cell

我輸入一個腳本,添加一個inputtype=text被點擊的TD內,與原值td在它的內部。

$(document).ready(function(){
    $('#med_table').on('click', '.tdSel', function() {
        var num_pills = ($(this).text());
        $(this).val("");
        var id = $(this).closest('tr').attr('id');
        console.log(id);
        $(this).replaceWith('<input type="number" id="test" class="form-control select" value='+num_pills+'>')
        $('#test').on('focusout', function()
        {
            var new_quantity = $(this).val();
            //console.log(new_quantity);
            //alert("out");
            //Ajax
        })
    });
})

我的問題是,如果我再次錯誤地單擊同一td則會添加另一個文本框。 我想要的是在單擊的td上添加一個單個文本框。

我試圖設置一個計數器:

$(document).ready(function(){
    var i = 0;
    $('#med_table').on('click', '.tdSel', function() {
        if(i==0)
        {
            var num_pills = ($(this).text());
            $(this).val("");
            var id = $(this).closest('tr').attr('id');
            console.log(id);
            $(this).replaceWith('<input type="number" id="test" class="form-control select" value='+num_pills+'>')
            $('#test').on('focusout', function()
            {
                var new_quantity = $(this).val();
                //console.log(new_quantity);
                //alert("out");
                //Ajax
            })
        }
        i++;
    });
})

它起作用了,但是現在我不能在其他tds添加文本框。

嘗試以下代碼:

HTML:

<table border = "1" width="100%">
  <tr>
    <td>2</td>
    <td>1</td>
    <td>3</td>
  </tr>
</table>

JS:

$(document).ready(function() {
    $("td").on("click", function() {
        var counter = $(this).attr("data-counter");
        if (counter != 1) {
            var data = $(this).text();
            $(this).html('<input type="number" id="test" class="form-control select" value=' + data + '>');
            $(this).attr("data-counter", "1");
        }
    });
});

這里嘗試現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM