
[英]How Can I set variable width with !importanat using JavaScript/jQuery
[英]How can I generate a link with a variable? Using javascript, jquery
我尝试创建一个 function 生成链接并将其添加到元素中。 但是.click function 不起作用。 我什至没有收到错误,这就是为什么我不确定 function 或变量是否错误的原因。
这是我的 javascript 代码:
$("#nwa1").click(function(){
var titel = document.getElementById("h1").innerHTML;
link = '';
link += 'nwa_' + titel + '.json'
$.getJSON(link, function(json){
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
for (i = 0; i < json.werte.length; i++){
aus += '<td>' + json.werte[i].kcal + '</td>' + '<td>' + json.werte[i].eiweiß + '</td>' + '<td>' + json.werte[i].fett + '</td>';
}
aus += '</tr></table>';
$('#div2').html(aus);
})
})
这是 html 页面:
<h4 id="nwa1">Nährwertangaben</h4>
<div id="div2" ></div>
我想用 function 打开的链接是 nwa_falafel.json 和“沙拉三明治”是我的 h1 元素。
谢谢你,试图帮助::)
这是 JSON 文件的路径问题。 尝试下面的(工作)代码并检查控制台以查看它是否正在记录错误。
$("#nwa1").click(function()
{
alert('genau!');
$titel = document.getElementById("h1").innerHTML;
$link = '';
$link += 'nwa_' + $titel + '.json'
$.getJSON( $link, {
format: "json"
})
.fail(function() {
console.log( "error" );
})
.done(function( data ) {
console.log("done");
console.log(data.werte);
aus = '';
aus += '<table border="1"><tr><th>Kcal</th><th>Eiweiß in g</th><th>Fett in g</th></tr>';
$.each( data.werte, function( i, item ) {
aus += '<td>' + item.kcal + '</td>' + '<td>' + item.eiweiß + '</td>' + '<td>' + item.fett + '</td>';
});
aus += '</tr></table>';
$('#div2').html(aus);
});
});
我在我身边添加了一些 colors 只是为了强调:
因此,如果您收到错误,请检查 JSON 文件的位置/路径,因为代码可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.