试图通过jquery选择器从最接近LI标签的隐藏字段中提取值



当用户点击btnShipNow按钮时,我试图捕获存储在隐藏字段hdnServiceCode中的值。这里粘贴一个html样本。我想当用户点击btnShipNow按钮时,然后我想从hdnServiceCode隐藏字段中提取最接近btnShipNow按钮的值。

这是我的html
<div id="rec">
<ul>
    <li>
    <input type="hidden" value="65" id="hdnServiceCode">
    UPS Express Saver</li>
</ul>
<ul>
    <li>24.47&nbsp;GBP</li>
    <li class="nobutton"><span id="rptPrice_ctl01_btnShipNow">Ship Now</span>
    </li>
</ul>
</div>
<div id="rec">
<ul>
    <li>
    <input type="hidden" value="15" id="hdnServiceCode">
    UPS Express Saver</li>
</ul>
<ul>
    <li>11.47&nbsp;GBP</li>
    <li class="nobutton"><span id="rptPrice_ctl01_btnShipNow">Ship Now</span>
    </li>
</ul>
</div>
这是我的jquery代码
$('.nobutton').live("click", function () {
        alert($(this).closest('ul').closest('div#rec').closest("hdnServiceCode").val());
    });

,但上面的代码不起作用。我在哪里出错了。请帮助我从最接近btnShipNow按钮的隐藏字段捕获值。由于

试试,

 alert($(this).closest('#rec').find("#hdnServiceCode").val());

可能你在选择器中有很多错误,比如

  • id选择器使用不当
  • 不必要地多次使用最近的

但是主要应该为DOM中的元素使用唯一的id。为当前id为hdnServiceCode的元素使用一个类,并使用

 alert($(this).closest('#rec').find(".hdnServiceCode").val());

这里有一个小提琴:http://jsfiddle.net/boatrokr/jB5a5/

我清理了匹配id的问题,并使用了这个:

$('.nobutton').click(function(){
    alert($(this).prev().text());
});

As id必须唯一。所以修改你的代码,并添加类hdn到你的字段

<div id="rec">
<ul>
    <li>
        <input type="hidden" value="65" id="hdnServiceCode1" class="hdn"/>
    UPS Express Saver</li>
</ul>
<ul>
    <li>24.47&nbsp;GBP</li>
    <li class="nobutton"><span id="rptPrice_ctl01_btnShipNow">Ship Now</span>
    </li>
</ul>
</div>
<div id="rec">
<ul>
    <li>
        <input type="hidden" value="15" id="hdnServiceCode2" class="hdn"/>
    UPS Express Saver</li>
</ul>
<ul>
    <li>11.47&nbsp;GBP</li>
    <li class="nobutton"><span id="rptPrice_ctl01_btnShipNow">Ship Now</span>
    </li>
</ul>
你jquery

$('.nobutton').on('click', function () {
        alert($(this).closest('#rec').find(".hdn").val());
    alert($(this).closest('#rec').find("ul:eq(0)  li").text());
    });

最新更新