简体   繁体   中英

Javascript onclick function error Cannot read property 'inv' of undefined

I have javascript function as below:

function myClickEvent(params) {
    var inv = $("#" + params["inv"]);
    inv.on("click", function () {
        $.ajax({
            url: params["route"],
            contentType: "text/json",
            success: function (result) {
                history.pushState(null, null, params["route"]);
                $("#content-wrapper").html(result);
                inv.parent().siblings().removeClass("active");
                inv.parent().addClass("active");
            }
        });
        return false;
    });
}

I am calling this into my html file like this:

<button onclick='myClickEvent()'>Click me</button>

It is showing error

Cannot read property 'inv' of undefined

How to test this function?

params is supposed to be a Javascript object with the inv property, which you have not provided as an argument to the function.

 function myClickEvent(params) { var inv = $("#" + params["inv"]); inv.on("click", function () { console.log(inv+": clicked"); //$.ajax({ // url: params["route"], //contentType: "text/json", //success: function (result) { // history.pushState(null, null, params["route"]); // $("#content-wrapper").html(result); // inv.parent().siblings().removeClass("active"); // inv.parent().addClass("active"); // } // }); // return false; }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick='myClickEvent({inv: "test"})'>Click me</button> <p/> <button id="test">Test</button> 

That's because you are not passing anything to the function, you can test it this way

<button onclick='myClickEvent("value")'>Click me</button>

and then add console.log(params) in the first line of your function

您需要阅读一个JavaScript教程,您告诉按钮在不带参数的情况下单击函数myClickEvent()即可执行该按钮,并且在定义中您期望的是params param,这本身并没有填充,我会告诉您添加参数,但您真正需要做的是不使用html中的onClick属性,而是使用button元素中脚本中的addEventListener。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM