jQuery: trying hook a function to the onclick when

2019-06-25 00:07发布

I am using jQuery to dynamically (I mean at runtime) add a span element to my page's DOM:

// create add task button
$(document.createElement("span"))
    .attr({ id: activityNameHyphened + "-NewButton", name: activityNameHyphened + "-NewButton" })
    .addClass("smallButton")
    .appendTo(cell1)
    .click(CreateTaskRow(ActivityName));

The problem is the last line: I thought it would add CreateTaskRow(ActivityName) as the handler for the onclick event of the span, just like:

<span onclick="CreateTaskRow(ActivityName);"></span>

which is what I want - but when I run it in the browser, I can see using the debugger that at this line it immediately runs the function instead.

If I can make it clearer: CreateTaskRow() runs when I'm trying to add it to the onclick (I want it to run only when the user actually clicks the span).

Any idea what I'm doing wrong? (and please let me know if my question isn't clear enough)

4条回答
贪生不怕死
2楼-- · 2019-06-25 00:25

You can define an event handler for elements you create before creating them using live() method.

$("span.smallButton").live("click", function () {
    CreateTaskRow(ActivityName);
});

Then when you create new element, you don't have to remember about hooking events to it.

$(document.createElement("span"))
    .attr({ id: activityNameHyphened + "-NewButton", name: activityNameHyphened + "-NewButton" })
    .addClass("smallButton")
    .appendTo(cell1);
查看更多
何必那么认真
3楼-- · 2019-06-25 00:30

.click triggers the click event, you must bind the function to the click event:

$("p").bind("click", function(e) {
      var str = "( " + e.pageX + ", " + e.pageY + " )";
      $("span").text("Click happened! " + str);
});
查看更多
在下西门庆
4楼-- · 2019-06-25 00:31

You are actually calling the function and passing the result to the .click() event handler. Try it with a closure (anonymous function) instead:

.click(function() {
    CreateTaskRow(ActivityName);
});

The closure will not be run until the click event is fired.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-06-25 00:34

Try with a closure

$("<span>")
    .attr({ id: activityNameHyphened + "-NewButton", name: activityNameHyphened + "-NewButton" })
    .addClass("smallButton")
    .appendTo(cell1)
    .click(function() { CreateTaskRow(ActivityName); });

Working Demo

Code from the demo -

$(function() {

  var activityNameHyphened = "id1";
  var ActivityName = "This is the highlighted activity";

  $('#clickMe').click(function() {

    $("<span>I've been added</span>")
        .attr({ id: activityNameHyphened + "-NewButton", 
              name: activityNameHyphened + "-NewButton" 
            })
        .addClass("smallButton")
        .appendTo("#here")
        .click(function() { CreateTaskRow(ActivityName); });        
  });    
});


function CreateTaskRow(e)
{
  alert(e);
}
查看更多
登录 后发表回答