点击使用jquery点击几个父元素的值

时间:2015-10-28 02:20:46

标签: jquery

这是我正在使用的HTML:

<ul id="sortable-row" class="ui-sortable">
        <li id="1" class="ui-sortable-handle">
            Dropdown Question:
            <input class="fieldtype" type="hidden" value="dropdown" name="fieldtype[]">
            <input class="amountofoptions" type="hidden" name="amountofoptions[]" value="2">
            <input class="questionname" type="text" name="questionname[]">
            <br>
            <button class="btn btn-primary adddropdownoptionbutton" type="button">add option</button>
            <ul class="dropdown-options-row">
                <li class="anoption">
                    Option:
                    <input class="dropdownoptionname" type="text" name="dropdownoptionname[]" value="">
                    <span class="ex">x</span>
                </li>
                <li class="anoption">
                    Option:
                    <input class="dropdownoptionname" type="text" value="" name="dropdownoptionname[]">
                    <span class="ex">x</span>
                </li>
            </ul>
        </li>
    </ul>

单击“x”时,我想获取“amountofoptions”的值。我尝试了很多不同的parent(),nearest()和sibling()变体,但是无法使用任何东西。我不能粘贴我尝试的所有不同的东西,因为我在其他地方。我现在在家里无法访问其他计算机,但我现在得到的任何建议我都可以在我的家用wamp服务器上测试(或者明天我回到其他计算机上)。

3 个答案:

答案 0 :(得分:3)

$(".ex").on("click",function(){ console.log($(this).closest( "ul" ).siblings(".amountofoptions").val()); }) 不是兄弟姐妹,也不是amountofoptions的父母,那么你需要得到最接近的父母ex amountofoptions元素。ul。然后,您可以使用siblings()prevAll()选择amountofoptions,如下所示:

$('.ex').click(function(){
  // for the best case, we use prevAll as we want
  // to select `amountofoptions` element that is located
  // before the UL element
  var a = $(this).closest('ul').prevAll('.amountofoptions').val();
  // or you can use below line of code using .find()
  var a = $(this).closest('.ui-sortable').find('.amountofoptions').val();
  // or this, this is worst but work, not recommended this
  var a = $(this).closest('ul').prev().prev().prev().val();
  // or by .siblings() like so :
  var a = $(this).closest( "ul" ).siblings(".amountofoptions").val()
  alert(a);
});

你可以选择以上4种方法中的1种,这里是 DEMO

答案 1 :(得分:1)

您可以尝试closest

喜欢这个

mag3

JSFIDDLE

答案 2 :(得分:0)

您不需要edges <- matrix(c(1, 2, 3, 2, 4, 1, 3, 4), byrow = TRUE, ncol = 2) coords <- matrix(c(0, 1, 1, 0, 0, -1, -1, 0), byrow = TRUE, ncol = 2) xyplot(coords[,2] ~ coords[,1], panel = function(...){adeg.panel.edges(edges, coords, lty = 1:4, cex = 5)}) 或任何其他遍历方法。我首先建议将每个parents()更改为<span>语义,然后应用<button>来区分两个按钮。代码可以承受,JS将是:

id