我一直在开发一个允许使用jquery编辑表行的应用程序。原帖是Targetting a <td> from it's parents <tr> with data-attributes using jquery
应用程序的流程是:
editBtn
)出现在每一行上。editBtn
并添加班级saveBtn
。该文字也改变了&#39;编辑&#39;到&#39;保存&#39;。目的是在单击“保存”按钮时,我可以执行ajax请求。
但是,我只能定位被点击的.saveBtn
,如果它的jquery位于{i>里面 .click
.editBtn
上的原始$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
var $td2 = $tr.find('td:nth-child(2)');
$td.html('<input value="' + $td.text() + '" />');
$td2.html('<button class="btn btn-primary btn-success saveBtn">Save</button>');
$('.saveBtn').click(function() {
console.log('savebtn');
});
});
函数。例如,这可行:
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
var $td2 = $tr.find('td:nth-child(2)');
$td.html('<input value="' + $td.text() + '" />');
$td2.html('<button class="btn btn-primary btn-success saveBtn">Save</button>');
});
// Moved outside $('.editBtn').click
$('.saveBtn').click(function() {
console.log('savebtn');
});
但这不工作:
var elixir = require('laravel-elixir');
require('laravel-elixir-vueify');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss')
.browserify('app.js')
.browserSync({proxy: 'mysite.dev'});
});
为什么会这样?
答案 0 :(得分:2)
它不起作用,因为在点击事件绑定后附加.savebtn。你必须在点击时使用文件。 这将有效: -
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
var $td2 = $tr.find('td:nth-child(2)');
$td.html('<input value="' + $td.text() + '" />');
$td2.html('<button class="btn btn-primary btn-success saveBtn">Save</button>');
});
// Moved outside $('.editBtn').click
$(document).on('click', '.saveBtn', function(){
console.log('savebtn');
});