我认为有一个基本的数据表。表列之一显示电话号码。我必须处理的所有数字都是十位数字,没有任何格式(例如破折号或括号)。
我想用包含此电话号码的链接替换所有这些号码。
我该如何去做呢?
<小时/>我根据这个问题尝试了一些东西: jquery, dynamically create link from text in td cell
我将代码替换为仅包含十位数字的正则表达式。这是我在包含 id="mydata"
的 HTML 表之后立即调用的脚本。该 View 仅包含此表和脚本:
<script>
$(document).ready( function () {
$('#mydata').click(function(){
var phone = $(this).find(/\d{10}/).text();
window.location.href = "http://somelink" + phone + ".jpg"
});
$('#mydata').DataTable( {
deferRender: true, // Renders only the rows that are visible
dom: 'frtiS', // Additional parameters. See docs.
scrollCollapse: true, // Collapses table if there are few results
scrollY: 700 // Height of the container
} );
} );
</script>
不幸的是,无论我在表格中单击什么位置,这些功能似乎都会触发,并且不会在链接中嵌入电话号码。
最佳答案
如果您有一列仅包含电话号码,则可以使用 columnDefs用于定位特定列并定义 columns.render 的选项当需要呈现该列中的数据时将调用的回调函数。
解决方案 1:在单列中呈现数据
例如,如果第二列(targets: 1
,索引从零开始)包含电话号码,请使用以下代码:
$(document).ready( function () {
$('#mydata').DataTable( {
deferRender: true, // Renders only the rows that are visible
dom: 'frtiS', // Additional parameters. See docs.
scrollCollapse: true, // Collapses table if there are few results
scrollY: 700, // Height of the container
columnDefs: [
{
targets: 1,
render: function(data, type, full, meta){
if(type === 'display'){
return '<a href="http://somelink' + data + '.jpg">' + data + '</a>';
} else {
return data;
}
}
}
]
} );
} );
演示
参见this jsFiddle用于演示。
<小时/>解决方案 2:渲染所有列中的数据
要呈现所有列中的数据,即使电话号码只是数据的一部分,也请使用下面的代码。
$(document).ready( function () {
$('#mydata').DataTable( {
deferRender: true, // Renders only the rows that are visible
dom: 'frtiS', // Additional parameters. See docs.
scrollCollapse: true, // Collapses table if there are few results
scrollY: 700, // Height of the container
columnDefs: [
{
targets: "_all",
render: function(data, type, full, meta){
if(type === 'display'){
return return data.replace(/(\d{10})/, "<a href=\"http://somelink$1.jpg\">$1</a>");
} else {
return data;
}
}
}
]
} );
} );
演示
参见this jsFiddle用于演示。
关于jquery - 用链接替换 DataTable 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31452663/