我尝试将图片链接添加到此javascript附加到表格中。这样图像就在按钮上方
这是代码
$("#1").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#1").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
任何想法都会很棒!
由于 萨姆
修改
这是代码
for(var i =0;i < json.results.length;i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='glaisdale.co.uk'>Compare</button>";
$('#1 .redirect-button').before('<img src="extreamlylongurlpathhere" alt=""></a>');
$("#1").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#1").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error: function(error){
console.log(error);
}
});
这也是愚蠢的代码。这是一个很大的混乱,我知道抱歉:)
答案 0 :(得分:0)
如果你想把链接图像放在按钮之前,你应该尝试使用jQuery .before()
。这样的事情应该有效:
$('#1 .redirect-button').before('<a href="#"><img src="#" alt=""></a>');
在评论中你解释了表格如何变得奇怪,原因似乎来自一个糟糕的html语法(链接的开头标记丢失):
$('#1 .redirect-button').before('<img src="extreamlylongurlpathhere" alt=""></a>');
但是,多亏了你的编辑,我现在可以看到before()
解决方案对于这种情况不是最好的。
最好将其删除并添加与添加button
完全相同的图像。
var button = "<button class='redirect-button' data-url='glaisdale.co.uk'>Compare</button>";
var linkImg = "<a href='#'><img src='extreamlylongurlpathhere' alt=''></a>";
$("#1").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+linkImg+button+"</td></tr></tbody>");
您可以在此处找到代码段:
/*fake JSON*/
var json = {};
json.results = [];
json.results = [{
section: 'a',
avalible: '1',
price: '12'
},{
section: 'b',
avalible: '2',
price: '12'
},{
section: 'c',
avalible: '3',
price: '12'
}];
/*loop*/
for(var i =0;i < json.results.length;i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='glaisdale.co.uk'>Compare</button>";
var linkImg = "<a href='#'><img src='extreamlylongurlpathhere' alt=''></a>";
//$('#1 .redirect-button').before('<a href="#"><img src="extreamlylongurlpathhere" alt=""></a>');
$("#1").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+linkImg+button+"</td></tr></tbody>");
$("#1").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
table {
width:100%;
}
table td, table tr{
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="1">
</table>