简体   繁体   中英

How to make an onlick event handler as a class method

I want to create a JavaScript class that has an onclick event handler as a method:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
  var foo = new Foo();
  foo.load();
});
function Foo() {
  function clicked() {
    alert('clicked');
  }
  this.load = function () {
    $('#container').html('<button onclick="clicked()">Press</button>');  
  }
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

But I get a scope error: Uncaught ReferenceError: clicked is not defined .

Why? How do I fix the scope and keep the event handler as a method of the class?

Create the button as an object, and assign the click handler directly:

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {
  var foo = new Foo();
  foo.load();
});
function Foo() {
  function clicked() {
    alert('clicked');
  }
  this.load = function () {
    var b = $('<button>');
    b.text('Press');
    b.on('click', clicked);
    $('#container').append(b);  
  }
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

Doing it this way keeps a reference directly to the function itself, as it's always in scope. By assigning it through the onclick attribute, it loses the scope of where it was declared.

您可以通过直接链接到函数来避免这种情况:

$('#container').html('<button>Press</button>').find('button').click(clicked);

Try this

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function () {

        foo.load();
});
var foo = new Foo();
function Foo() 
{
this.clicked=clicked;
function clicked() 
{
        alert('clicked');
}

this.load = function () 
{
        $('#container').html('<button onclick="foo.clicked();">Press</button>');  
}
}
</script>
</head>
<body>
  <div id="container"></div>
</body>
</html>

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