[英]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.