- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 Web 应用程序从一个 JSON 对象获取值,并用它的值填充一个表,每行都有一个编辑和删除按钮。我希望我的脚本能够知道按下了哪些行编辑按钮,以及这些行的单元格值。
在格式化我的问题时,我偶然发现了这个完全相同的问题(我搜索了一个小时才决定提问),但它不包含任何对我有用的解决方案: Get Value of HTML cells in row clicked with Javascript
HTML:
<div class="container">
<h4>Persons</h4>
<div class="table-responsive">
<table class="table table-striped" id="persons_table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
//dynamically generated rows goes here
</tbody>
</table>
</div>
<button class="btn btn-sm btn-primary" id="addBtn">New person</button>
</div>
填充表格的函数:
function handlePersons(data){ //data is a response from an API (JSON)
var table = document.getElementById('persons_table');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML =
'<td>' + object.ID + '</td>' +
'<td>' + object.Info.Name + '</td>' +
'<td>' + object.Info.Email + '</td>' +
'<td>' + object.Info.PhoneNumber + '</td>' +
'<td><p data-placement="top" data-toggle="tooltip" title="Edit">
<button class="btn btn-primary btn-xs" id="editBtn" data-title="Edit" data-toggle="modal" data-target="#edit">
<span class="fa fa-pencil"></span></button></p></td>' +
'<td><p data-placement="top" data-toggle="tooltip" title="Delete">
<button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete">
<span class="fa fa-trash"></span></button></p></td>';
table.appendChild(tr);
});
}
以防万一你需要它,这是我获取 JSON 数据的 ajax 调用:
function getPersons(){
var settings = {
"async" : true,
"crossDomain" : true,
"url" : "...",
"method" : "GET",
"headers" : {
"Content-Type" : "application/json",
"Authorization": "...",
"cache-control" : "no-cache"
},
"processData" : false,
"data" : ""
}
return $.ajax(settings);
}
函数调用:
getPersons().done(handlePersons)
我的问题是,当我按下第一行的编辑按钮时,如何让我的脚本知道按下的是特定行上的编辑按钮,以及我如何才能知道例如 console.log 行名称(约翰)?这是我试过的:
$('#editBtn').on('click', () => {
var par = $(this).parent().parent(); //to choose table row, also tried one
//and three .parent() because I don't
//quite understand this
var namevalue = par.children("td:nth-child(2)").val(); //also tried with .text()
console.log(namevalue); //.val = undefined and .text = empty string
});
$('#editBtn').on('click', () => { //also tried with onclick="function"
//on the button instead of
//jQuery just in case
var tr = $(this).closest('tr')
var tdID = $(tr).find('td').eq(0).text();
var tdName = $(tr).find('td').eq(1).text();
var tdEmail = $(tr).find('td').eq(2).text();
var tdPhone = $(tr).find('td').eq(3).text();
console.log(tdName); //.text logs empty string, .val logs undefined again
});
@Cybernetic 请求后的 JSON 数据。对其进行了一些编辑以不泄露任何敏感信息,但在我的代码中应该仍会产生相同的结果。
[
{
"CustomValues": {},
"Comment": "Here is John",
"Deleted": false,
"ID": 1,
"InfoID": 4,
"Role": null,
"StatusCode": null,
"UpdatedAt": null,
"UpdatedBy": null,
"Info": {
"DefaultEmailID": 1,
"DefaultPhoneID": 2,
"Deleted": false,
"ID": 3,
"Name": "John",
"PhoneNumber": "123-123-123",
"Email": "john@mail.com"
}
},
{
"CustomValues": {},
"Comment": "Here is Mike",
"Deleted": false,
"ID": 2,
"InfoID": 6,
"Role": null,
"StatusCode": null,
"UpdatedAt": null,
"UpdatedBy": null,
"Info": {
"DefaultEmailID": 3,
"DefaultPhoneID": 4,
"Deleted": false,
"ID": 6,
"Name": "Mike",
"PhoneNumber": "321-321-321",
"Email": "mike@mail.com"
}
}
]
最佳答案
由于使用了 jQuery,因此您应该遵循两个未记录的规则:
Do not use id unless required (such as Bootstrap
data-
attributes), use class. Note: The demo below demonstrates how we can use class exclusively and no longer have any dependency on ids.Do not use on-event attributes
<button
onclick="fnc()">
第一条规则适用于演示,第二条规则不相关,只是为了完整性而添加。此外,ID 必须是唯一的——提供的 OP 代码生成了重复的 button#editBtn
.
动态添加的元素无法绑定(bind)到事件,因此任何向编辑/删除按钮添加“点击”事件的尝试都会失败。只有加载时存在的元素才能注册到事件中,因此 <tbody>
中的任何祖先元素至 document
可以注册到点击事件,然后事件可以委托(delegate)给编辑/删除按钮。一般而言,委托(delegate)事件涉及用于具体确定哪些元素对事件作出 react 以及哪些元素忽略此类事件的编程模式。
jQuery 事件方法通过提供名为 .on()
的第一个(eventData
的第二个)参数使事件委托(delegate)变得容易。 . eventData
是选择器字符串格式的可选参数(与 $(
... )
中常用的相同)。这将成为函数的上下文 -- $(this)
或 $(event.target)
-- 本质上是点击按钮。
祖先 事件数据
⇩ ⇩
$(document).on('click', '.edit', function(e) {...
演示中评论的细节
/*
A: jQuery .append() is not destructive like .innerHTML
Template literal is easier and cleaner than literal
strings.
*/
function handleContacts(data) {
data.forEach(function(object) {
$('.contacts').append(`<tr>
<td class='content'>${object.ID}</td>
<td class='content'>${object.Info.Name}</td>
<td class='content'>${object.Info.Email}</td>
<td class='content'>${object.Info.PhoneNumber}</td>
<td><button class="btn btn-primary btn-xs edit"><i class="fas fa-pen"></i></button></p></td>
<td><button class="btn btn-danger btn-xs delete"><i class="fas fa-trash"></i></button></td></tr>`); //A
});
}
var data = [{
"CustomValues": {},
"Comment": "Here is John",
"Deleted": false,
"ID": 1,
"InfoID": 4,
"Role": null,
"StatusCode": null,
"UpdatedAt": null,
"UpdatedBy": null,
"Info": {
"DefaultEmailID": 1,
"DefaultPhoneID": 2,
"Deleted": false,
"ID": 3,
"Name": "John",
"PhoneNumber": "123-123-1231",
"Email": "john@mail.com"
}
},
{
"CustomValues": {},
"Comment": "Here is Mike",
"Deleted": false,
"ID": 2,
"InfoID": 6,
"Role": null,
"StatusCode": null,
"UpdatedAt": null,
"UpdatedBy": null,
"Info": {
"DefaultEmailID": 3,
"DefaultPhoneID": 4,
"Deleted": false,
"ID": 6,
"Name": "Mike",
"PhoneNumber": "321-321-3213",
"Email": "mike@mail.com"
}
}
];
// button.add is clicked -- handleContacts() is called
$('.add').on('click', function(e) {
handleContacts(data);
});
/*
Delegate click event to document
$(this) or $(e.target) is button.delete
Get the .closest() <tr> and remove() it.
*/
$(document).on('click', '.delete', function(e) {
$(e.target).closest('tr').remove();
});
/*
Delegate click event to document
Note: Any dynamically added elements cannot be bound to
events. Events must be bound to an element that
existed at load time.
$(this) or $(e.target) is button.edit
*/
/*
B: Get the .closest() <tr>
C: In this <tr> find() .each() td.content and toggle the
[contenteditable] attribute true/false
D: In this <tr> find() td[contenteditable] and .focus() on
the first one .eq(0). Note: $(this)[0] is a dereferenced
"this" because jQuery will not recognize the JavaScript
method .toggleAttribute()
*/
$(document).on('click', '.edit', function(e) {
var row = $(e.target).closest('tr'); //B
row.find('.content').each(function() {
$(this)[0].toggleAttribute('contenteditable');
}); //C
row.find('[contenteditable]').eq(0).focus(); //D
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" crossorigin="anonymous">
<div class="container">
<div class="table-responsive">
<table class="table table-striped contacts">
<caption style='caption-side:top'><h4>Contacts</h4></caption>
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button class="btn btn-sm btn-primary add">Add Contacts</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
关于javascript - 从动态填充表 JavaScript 中的特定行获取特定单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786594/
我需要您在以下方面提供帮助。近一个月来,我一直在阅读有关任务和异步的内容。 我想尝试在一个简单的 wep api 项目中实现我新获得的知识。我有以下方法,并且它们都按预期工作: public Htt
我的可执行 jar 中有一个模板文件 (.xls)。不需要在运行时我需要为这个文件创建 100 多个副本(稍后将唯一地附加)。用于获取 jar 文件中的资源 (template.xls)。我正在使用
我在查看网站的模型代码时对原型(prototype)有疑问。我知道这对 Javascript 中的继承很有用。 在这个例子中... define([], function () { "use
影响我性能的前三项操作是: 获取滚动条 获取偏移高度 Ext.getStyle 为了解释我的应用程序中发生了什么:我有一个网格,其中有一列在每个单元格中呈现网格。当我几乎对网格的内容做任何事情时,它运
我正在使用以下函数来获取 URL 参数。 function gup(name, url) { name = name.replace(/[\[]/, '\\\[').replace(/[\]]/,
我最近一直在使用 sysctl 来做很多事情,现在我使用 HW_MACHINE_ARCH 变量。我正在使用以下代码。请注意,当我尝试获取其他变量 HW_MACHINE 时,此代码可以完美运行。我还认为
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 关闭 9 年前。 要求提供代码的问题必须表现出对所解决问题的最低限度的理解。包括尝试过的解决方案、为什么
由于使用 main-bower-files 作为使用 Gulp 的编译任务的一部分,我无法使用 node_modules 中的 webpack 来require 模块code> dir 因为我会弄乱当
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我使用 Gridlayout 在一行中放置 4 个元素。首先,我有一个 JPanel,一切正常。对于行数变大并且我必须能够向下滚动的情况,我对其进行了一些更改。现在我的 JPanel 上添加了一个 J
由于以下原因,我想将 VolumeId 的值保存在变量中: #!/usr/bin/env python import boto3 import json import argparse import
我正在将 MSAL 版本 1.x 更新为 MSAL-browser 的 Angular 。所以我正在尝试从版本 1.x 迁移到 2.X.I 能够成功替换代码并且工作正常。但是我遇到了 acquireT
我知道有很多关于此的问题,例如 Getting daily averages with pandas和 How get monthly mean in pandas using groupby但我遇到
This is the query string that I am receiving in URL. Output url: /demo/analysis/test?startDate=Sat+
我正在尝试使用 javascript 中的以下代码访问 Geoserver 层 var gkvrtWmsSource =new ol.source.ImageWMS({ u
API 需要一个包含授权代码的 header 。这就是我到目前为止所拥有的: var fullUrl = 'https://api.ecobee.com/1/thermostat?json=\{"s
如何获取文件中的最后一个字符,如果是某个字符,则删除它而不将整个文件加载到内存中? 这就是我目前所拥有的。 using (var fileStream = new FileStream("file.t
我是这个社区的新手,想出了我的第一个问题。 我正在使用 JSP,我成功地创建了 JSP-Sites,它正在使用jsp:setParameter 和 jsp:getParameter 具有单个字符串。
在回答 StoreStore reordering happens when compiling C++ for x86 @Peter Cordes 写过 For Acquire/Release se
我有一个函数,我们将其命名为 X1,它返回变量 Y。该函数在操作 .on("focusout", X1) 中使用。如何获取变量Y?执行.on后X1的结果? 最佳答案 您可以更改 Y 的范围以使其位于函
我是一名优秀的程序员,十分优秀!