total jquery/programming newbie here.
我有一堆可以选择的文本框。选中该框后,我想将新行附加到我的表中,并将文本框中的 h4 添加到新行的第一列中。变量有一些问题。
文本框如下所示:
<div class="boxed" data-price="7">
<h4 class="boxTitle">Lemons</h4>
<p>blahblahblah</p>
</div>
表格如下所示:
<tbody>
<table class="table table-hover" id="theOrder">
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Product1</td>
<td><input type="text" class="form-control" value="1"></td>
</tr>
<tr>
<td>Product2</td>
<td><input type="text" class="form-control" value="1"></td>
</tr></table></tbody>
我的jquery看起来像这样,但是我怎样才能让它打印我的变量productName而不是字符串?
$(document).ready(function() {
$( ".boxed" ).click(function( event ) {
var productName = $(this).find('.boxTitle');
// highlighting - this works fine
$(this).toggleClass("highlightedBox");
productName.toggleClass("boxTitleHl");
// adds new row to the end of the table
$('#theOrder').append('<tr><td class="newLine">productName</td><td><input type="text" class="form-control" value="1"></td></tr>');
});
});
我什至尝试这样做,但它只是打印出[对象][对象]。我不知道为什么。我需要将对象转换为字符串吗?
$('#theOrder').append('<tr><td class="newLine">zzzz</td><td><input type="text" class="form-control" value="1"></td></tr>');
$(".newLine").text(productName);
做了一个抖动!! http://jsfiddle.net/hBuck/
您可以使用
jQuery text()
或html()
来获取标签内的内容
改变
var productName = $(this).find('.boxTitle');
自
var productName = $(this).find('.boxTitle').html();
或
var productName = $(this).find('.boxTitle').text();
还要更改此行
$('#theOrder').append('<tr><td class="newLine">'+productName+'</td><td><input type="text" class="form-control" value="1"></td></tr>');
试试这个代码
$( ".boxed" ).click(function( event ) {
var puddingN = $(this).find('.boxTitle');
puddingName=puddingN.text();
// highlight the box and the pudding name
$(this).toggleClass("highlightedBox");
puddingN.toggleClass("boxTitleHl");
// TEST: changes title of table to pudding name..
$(".orderTitle").text(puddingName);
// adds new row to the end of the table
//$('#theOrder').append('<tr><td class="newLine">EEEEK</td><td><input type="text" class="form-control" value="1"></td></tr>');
// changes text to the name of the pudding but doesn't work :()
//$(".newLine").text(puddingName);
$('#theOrder').append('<tr><td class="newLine">'+puddingName+'</td><td><input type="text" class="form-control" value="1"></td></tr>');
});
小提琴演示
你需要将字符串与变量连接
起来var productName = $(this).find('.boxTitle').text();
$('#theOrder').append('<tr><td class="newLine">'+productName+'</td><td><input type="text"
class="form-control" value="1"></td></tr>');