事件委托-无法更改按钮的类和值

时间:2018-09-15 17:42:38

标签: javascript event-delegation

我正在尝试使用香草javascript禁止用户并删除其禁令。我正在使用数据表,因此必须使用事件委托来触发事件。

但是当我完成禁止用户操作后,我无法更改按钮的类或值,该怎么做?

document.querySelector(".m-portlet__body").addEventListener("click", function (e) {
        if (e.target.className === "btn btn-danger btn-sm btn-block") {
            console.log(e.target)
            let id = e.target.dataset.id,
                xhr = new XMLHttpRequest(),
                token = document.head.querySelector("[name=csrf-token]").content;
            xhr.open("POST", "users/ban/" + id);
            xhr.setRequestHeader("X-CSRF-TOKEN", token);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    let response = JSON.parse(xhr.responseText);
                    if (xhr.status === 200 && response.status === 'OK') {
                        e.target.className.replace("btn-danger","btn-success");
                        e.target.value = "Remove Ban"
                //I also try with;
                //e.target.classList.remove("btn-danger");
                //e.target.classList.add("btn-success");
                    } else {
                        console.log('failed');
                    }
                }
            }
            xhr.send();
        }

        if (e.target.className === "btn btn-success btn-sm btn-block"){

        }
    })

1 个答案:

答案 0 :(得分:2)

JS字符串是不可变的,这意味着String#replace不会替换原始字符串,而是返回一个新字符串。

class OrdersController < ApplicationController
  def new
    @order = Order.new
  end

  def create
    @order = Order.new(order_params)
    if @order.save
      render json: @order, status: :created
    else
      render :head, status: :unprocessable_entity
    end
  end

  private

  def order_params
    params.require(:order).permit(:name, components_attributes: [:name])
  end
end

将更改e.target.className值

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

如果目标是按钮元素而不是 e.target.className = e.target.className.replace("btn-danger","btn-success") ,则无法使用e.target.value更改其文本内容,需要使用e.target.textContent =“ New value”;