Jquery无法在内联html脚本上调用函数

时间:2015-12-09 23:53:10

标签: javascript jquery html

我尝试使用自定义函数删除element,该函数在我的脚本代码中内联html内调用,请参阅下面的代码:

HTML

<div id="form">
  <input type="text" name="name", id="name"><br>
  <input type="text" name="address", id="address"><br>
  <br>
  <button id="save">Save</button>
</div>

<br><br>

<table border="1">
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Unique ID</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody id="content">
  </tbody>
</table>

的Javascript

var data = [];

console.log('Initial Data: ');
console.log(data);

$('#save').click(function() {
    var unique_id = new Date().getUTCMilliseconds();
    var returnData = "<tr><td>" + $('#name').val() + "</td><td>" + $('#address').val() + "</td><td>"+unique_id+"</td><td><span onclick='this.removeThis("+unique_id+")'>X</span></td></tr>";
    data.push({
        name: $('#name').val(),
        address: $('#address').val(),
        unique_id: unique_id
    });
    $('#name').val('');
    $('#address').val('');
    console.log('Updated: ');
    console.log(data);
    $('#content').append(returnData);
});

function removeThis(unique_id){
  alert(unique_id);
}
控制台说:

Uncaught TypeError: this.removeThis is not a function

当我用this.removeThis

更改removeThis时,会发生同样的事情

以下是Fiddle

有什么想法吗?感谢。

3 个答案:

答案 0 :(得分:4)

您收到错误是因为JSFiddle默认将您在“javascript”部分输入的所有代码放入onload事件,这意味着您的removeThis函数不在全局范围内,并且对于您的内联javascript不可见。它也是removeThis()而不是this.removeThis()

https://jsfiddle.net/w2f7dux7/

答案 1 :(得分:0)

(P.S。)在jsFiddle选项中使用DOM ready
代码的更好变体:

<强> jsFiddle demo

var $content = $("#content"),                         // Cache your elements!
    $name    = $("#name"),
    $address = $("#address"),
    data     = [];

function createNewTR() {                              // Helpful function naming

  var name      = $name.val(),                        // Get values
      address   = $address.val(),                     // Get values
      unique_id = new Date().getUTCMilliseconds(),    // UID? whatever...
      $tr       = $("<tr/>", {                        // New ($)TRElement
                   appendTo: $content,                // Where do I go?
                   html: "<td>"+ name +"</td>      \
                          <td>"+ address +"</td>   \
                          <td>"+ unique_id +"</td> \
                          <td></td>"
                   });

  $("<span/>", {                                     // Tell immediately to your SPAN
      html: "X",                                     // what's he's supposed to do:
      appendTo: $tr.find("td:last"),                 // Where to get appended and
      click: function(){ $tr.remove(); }             // remove our $tr element on click
  });

  data.push({
    name:      name,
    address:   address,
    unique_id: unique_id
  });

  $name.add( $address ).val("");
}

$('#save').click(createNewTR);

答案 2 :(得分:0)

尝试将数据属性与关联的事件处理程序一起使用:

'<span data-unique-id="' + unique_id + '">X</span>'

当您附加字符串或创建#content时,您附加了单击事件的事件处理程序。 (它只够一次)

$('#content').append(returnData);

// "this" will be the current dom span in the event handler function, where the event occured
var self = this;

// attach event handler on every span that is in #content (if you need only one type of them, you need to use a class, or attribute selector
$('#content span').click(
    function(event)
    {
        self.removeThis( $(this).attr("data-unique-id") );
    }
);