如何从jquery中的循环元素中获取特定值

时间:2012-12-27 09:08:32

标签: jquery html

我循环使用我的html,并希望在用户点击按钮时获得特定的字段值。 我正在寻找正确的价值,请帮助我。

<div id="tabs1">
<table>
{foreach from=$this->products item=p}               
<tr>
<td><div class="tabs-product">
<div>
<input type='hidden' id='item' name='item' value='{$p.name}'/>
<input type='hidden' id='price' name='price' value='{$p.price}'/>
<button class="shareButton" onclick='post(); return false;'>Share</button>
</div></td></tr>
{/foreach}
</table></div>

<script>
 function post() {
    var item =  $(this).parent("tabs-product").attr("input");//this cause undefined
    var price = $('#price').val(); //this method only get first value
    alert(item + price);
}
</script>

3 个答案:

答案 0 :(得分:3)

var $product = $(this).closest('.tabs-product');
var item = $product.find('input[name="item"]').val();
var price = $product.find('input[name="price"]').val();
  • input是一个元素,而不是一个属性。
  • 您不能使用$('#price')中的绝对ID,因为您有多个具有相同ID的元素(通过循环打印) - 它既不符合规范(但是由不严格的浏览器允许),也没用
  • 使用input[name="..."]选择器,您可以查明实​​际需要的产品中的input元素。
  • 在这种情况下,parentclosest同样有效,但我更喜欢closest这些案例的灵活性,如果你改变了对结构的看法并决定插入一个额外的元素,用于布局或其他任何原因。 编辑:正如TJ在评论中指出的那样,我错过了<div>,这只是推动了这一点。

答案 1 :(得分:1)

您需要在代码中进行一些基本更正。

  • click事件与jQuery绑定,以便$(this)获取jQuery对象。

  • 您还需要使用。对于类选择器。在您的代码parent("tabs-product")中应该是parent(".tabs-product")

  • div与类标签 - 产品不是按钮的父级,而是您需要转到父级td并找到项目和价格。

  • id应该在页面中是唯一的,您将重复项目和价格的相同ID。
  

$( 'shareButton')。点击(函数(){

    var item =  $(this).closest('td').find("#item").va();//undefined
    var price = $(this).closest('td').find("#price").va()
    alert(item + price);     
     

});

要使用javascript onclick binding,您需要传递源对象并将其转换为post中的jQuery对象。

<button class="shareButton" onclick='post(this); return false;'>Share</button>

function post(obj) {
     var item =  $(this).closest('td').find("#item").va();//undefined
    var price = $(this).closest('td').find("#price").va()
    alert(item + price);
}

答案 2 :(得分:-1)

好吧,因为我看到你的代码,你做错了。你迭代并创建具有相同ID的元素,这根本不是很好的练习。所以我建议您使用class属性并使用Jquery.first()

<div id="tabs1">
<table>
{foreach from=$this->products item=p}               
<tr>
<td><div class="tabs-product">
<div>
<input type='hidden' class='item' name='item' value='{$p.name}'/>
<input type='hidden' class='price' name='price' value='{$p.price}'/>
<button class="shareButton" onclick='post(); return false;'>Share</button>
</div></td></tr>
{/foreach}
</table></div>

<script>
 function post() {
    var item =  $(this).parent("tabs-product").attr("input");//undefined
    var price = $('.price').first().val(); //get only first value
    alert(item + price);
}
</script>

其他人的答案还可以,但有多个相同的ID并不是真的很好,特别是在使用Jquery时

JQuery.first()参考 http://api.jquery.com/first/

JQuery.first() {{1}}

的{{1}}示例用法