Вы должны написать событие щелчка, когда объектная модель документа (DOM) готова.
См. Это
Просто сделайте это.
function addClickEvent() {
$(document).on('click', 'btn_selector', function () {
$(this).closest('tr').css("background-color", "#bbf6c5");
});
$(function () {
addClickEvent();
});
}
Видите, я сделал это на своем конце.
![enter image description here](https://i.stack.imgur.com/M23v6.png)
Выполните этот шаг:
(1) маршруты
Route::group(['prefix' => 'example'], function () {
Route::get('', 'ExampleController@view');
Route::get('get_table_data', 'ExampleController@get_table_data');
});
(2) контроллер
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use DataTables;
use App\Utility;
class ExampleController extends Controller {
public function view() {
return view('pages.store_admin.example-table');
}
function get_table_data() {
return DataTables::eloquent(Utility::query())->toJson();
}
}
(3) просмотр
@extends('layouts.store_admin')
@section('title','Example')
@section('page-title','Example')
@section('page-title-desc','')
@section('css')
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/dt-1.10.15/datatables.min.css"/>
@endsection
@section('content')
<div class="row">
<div class="card">
<div class="card-body">
<div class="col-lg-12 col-md-12">
<div class="table-responsive">
<table class="table table-ordered" id="example_table" style="width: 100%">
<thead style="font-weight: bold;">
<tr>
<td>ID</td>
<td>Key</td>
<td>Value</td>
<td>Action</td>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('js')
<script type="text/javascript" src="https://cdn.datatables.net/v/bs/dt-1.10.15/datatables.min.js"></script>
<script type="text/javascript">
<?php
$data_url = url('example/get_table_data');
?>
window.data_url = '{{ $data_url }}';
</script>
<script type="text/javascript" src="{{ asset('js/store_admin/example-table.js') }}"></script>
@endsection
(4) js
$(function () {
addDataTable();
addClickEvent();
});
function addDataTable() {
window.example_table = $('#example_table').DataTable({
processing: true,
serverSide: true,
targets: 0,
stateSave: true,
ajax: {
url: window.data_url
},
columns: [
{
data: 'id',
visible: false,
orderable: false,
searchable: false
},
{
data: 'key',
orderable: true,
searchable: true
},
{
data: 'value',
orderable: true,
searchable: true
},
{
data: 'id',
name: 'action',
orderable: false,
searchable: false,
render: function (data, type, row) {
return '<button class="btn btn-sm btn-danger change-red-color-btn">Red</button>'
+ ' <button class="btn btn-sm btn-success change-green-color-btn">Green</button>';
}
}
]
});
}
function addClickEvent() {
$(document).on('click', '.change-red-color-btn', function () {
$(this).closest('tr').css("background-color", "red");
});
$(document).on('click', '.change-green-color-btn', function () {
$(this).closest('tr').css("background-color", "green");
});
}