通过JSON将val设置为td

Set val to td by JSON

本文关键字:td 设置 val JSON 通过      更新时间:2023-09-26

尝试从JavaScript JSON中设置td值。但当我检查元素时,它似乎不起作用。然而,html的工作只是不值。不知道是什么问题。我也试过把id改成class,但是效果不太好。

$(document).ready(function(){
$(".login_a").click(function(){
    var test = $(this).attr('data-id');
    var topost = 'getMilestoneDetail.php='+test;
    var returnResults = $.getJSON('getMilestoneDetail.php?id='+test,function(data)
    {
        $("#td_projectName").html(data.projectName);
        $("#budget_amt").html(data.budget);
        $("#milestone_1").html(data.mileStone1);
        $("#percentage_1").html(data.percentage1);
        $("#percentage_1").val(data.percentage1);

    });
});
</script>
<div id="login_form">
<table border=1>
<tr>
<th> Project Name </th>
<td id="td_projectName">
</td> 
</tr>
<tr>
<th> Budget</th>
<td id="budget_amt"> 
</td>
</tr>
<tr>
<th>Stages</th>
<th>Payment Percentage</th>
</tr>
<tr>
<td id="milestone_1"> 
</td>
<td id="percentage_1">
</td>
</tr>

VAL不是TD的有效属性,这就是您不能设置它的原因。如果希望将某些数据存储为节点的属性,则使用setAttribute来存储它。例子:

直JS:

document.getElementById('percentage_1').setAttribute('bob', 'your uncle');

或使用jQuery:

$('#percentage_1').attr('bob', 'your uncle');

您将使用getAttribute或.attr稍后获取值,例如

var bob = document.getElementById('percentage_1').getAttribute('bob');

$('#percentage_1').attr('bob');

请注意,非标准属性不会验证,并且可能不受欢迎,但在web应用程序中是常见的固定装置。你可以使用jQuery的。data方法来正确设置节点上的数据,如果你不关心旧浏览器的支持

.val(value)方法主要用于设置表单元素的值,如input, select and textarea

您可以使用隐藏字段来保留值,也可以使用.text()方法来获取td的文本。

<td id="percentage_1">
    <input type="hidden" id="percentage_1_val" />
</td>
$("#percentage_1_val").val(data.percentage1);

获取值

$("#percentage_1_val").val(); 
// or you can use $("#percentage_1").text();