我打印数据库的结果。当我想从行中选择值时,我遇到了问题。我试图通过在值上输入按钮(最后一列)来获取该值,并将该值插入本地存储中。
<table class="table table-bordered">
<thead>
<tr class="bg-grey">
<th>Broj </th>
<th>Boja </th>
<th>Količina</th>
<th><center><i class="icon-cart"></i></center></th>
</tr>
</thead>
<tbody>
<?php
while ($r=$m->fetch()) {
$id_print = $r['id'];
$boja = $r['Boja'];
$kolicina = $r['Kolicina'];
// var_dump($id_print);
?>
<tr>
<td><?php echo "R - " . $id_print;?></td>
<td><?php echo $boja;?></td>
<td><?php echo $kolicina;?></td>
<td><button id= "item" value='<?php echo $id_print;?>' onclick="save()" class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
我正在使用函数从 td 获取值。但我总是得到空变量。
<script type="text/javascript">
function save() {
var items= document.getElementById('item').innerHTML;
localStorage.setItem('action', items);
}
</script>
我没有做好事,如果有人可以告诉我要改变什么才能获得结果。
最佳答案
如果您的目标是保存所单击按钮的值,则根本不需要任何 id
。
最小更改方法是将 this
作为参数传递到处理程序中,然后在处理程序的代码中使用该参数的 value
属性:
<td><button value='<?php echo $id_print;?>' onclick="save(this)" class="ion-ios-cart-outline"></button></td>
<!-- Note ------------------------------------------------^^^^^ -->
然后
function save(element) {
localStorage.setItem('action', element.value);
}
您还可以考虑将 type="button"
添加到 button
元素,因为 button
的默认 type
code>s 是(对我来说,令人惊讶的是)type="submit"
,所以如果表单中有这些按钮,它们就会提交表单。
回复您的评论:
That is exactly what I was looking for, but in table I have more rows and more could be selected. By doing this only one value is possible to select. Is it possible so save values in local storage by clicking on them
如果你的意思是作为一个数组,是的,你可以这样做。这是一种方法:
function save(element) {
var actions = JSON.parse(localStorage.getItem("actions") || "[]");
if (actions.findIndex(element.value) == -1) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}
}
它将本地存储中的数组维护为 JSON(因为所有本地存储值都是字符串)。第一部分获取现有数组(如果有)或空白数组(如果没有):
var actions = JSON.parse(localStorage.getItem("actions") || "[]");
然后我们使用 ES2015(又名“ES6”)函数 Array#findIndex
(可以进行填充/填充,请参阅 MDN )来查看该值是否已在数组中,并且,如果没有,我们添加它:
if (actions.findIndex(element.value) == -1) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}
如果出于某种原因您不想填充/填充 Array#findIndex
,您可以使用 ES5 函数 Array#some
来代替:
if (!actions.some(function(e) { return e === element.value; })) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}
关于javascript - 从 td 获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37655958/