试图创建一个带按钮的表来删除每一行,但它只适用于一行(javascript)?

时间:2015-11-16 05:44:54

标签: javascript

这是我的javascript,一旦我点击一个按钮就会移除该行,但其他按钮则什么都不做。

    private void calculateAndShow(double wt, double rt, double mk) {
    String w = weightLine.getText().toString();
    wt = Double.parseDouble(w);
    double NetRate = (double) Math.round((rt + mk) * 100.0) / 100.0;
    double Total = (double) Math.round(((NetRate / 10) * wt) * 100.0) / 100.0;

    netRate.setText(NetRate + "");
    itemtotal.setText(Total + "");
}

private TextWatcher rateTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String rate = rateAmount.getText().toString();
        rt = Double.parseDouble(rate);
        calculateAndShow(wt, rt, mk);
        rates.add(rate);
    }
};

private TextWatcher mkAmountTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String mkAmt = makingAmount.getText().toString();
        mk = Double.parseDouble(mkAmt);
        calculateAndShow(wt, rt, mk);
        mkCharges.add(mkAmt);

    }
};

继承我的HTML:

var removeRowBtns = document.getElementsByClassName("removeRowBtn")
var tableRows = document.getElementsByTagName("tr")

for(var i = 0; i < removeRowBtns.length; i++) {
removeRowBtns[i].addEventListener("click", function() {
  tableRows[i].parentNode.removeChild(tableRows[i]);
    });
}

1 个答案:

答案 0 :(得分:1)

您的事件处理程序在循环结束后执行很长时间。

您的变量i始终是循环的最后一个值。将按钮与您需要删除的表行相关联,并使用事件处理程序的e.target来获取对它的引用。

例如,您可以使用此类型的标记:

<tr id="r15"></tr>  <input type="button" rawLink="r15" value="Delete"></input>

和JS一样

for(var i = 0; i < removeRowBtns.length; i++) {
   removeRowBtns[i].addEventListener("click", function(e) {
      var raw = document.getElementById(e.target.getAttribute("rawLink"));
      raw.parentNode.removeChild(raw);
    });
}