2015-12-22 56 views
0

我希望能夠選擇最接近包含匹薩選擇選項的fieldset的h2標題,並使用jQuery設置標題的文本。到目前爲止,我無法做到這一點。無法使用JavaScript選擇最接近的h2元素

HTML:

<div id="pizzaForm"> 
     <fieldset> 
      <form class="pure-form"> 
      <legend>Pizza</legend> 
      <label><b>Pizza Type: &nbsp;</b></label> 
      <select id="pizza"> 
       <option name="margarita">Margarita</option> 
       <option name="deep-pan">Deep Pan</option> 
       <option name="stuffed-crust">Stuffed Crust</option> 
      </select> 
       <span style="float:right"> 
       <label><b>Pizza Size: &nbsp;</b></label> 
       <select id="pizzaSize"> 
        <option name="e-small" data-price="4.99">Extra Small - £4.99</option> 
        <option name="small" data-price="5.99">Small - £5.99</option> 
        <option name="medium" data-price="6.99">Medium - £6.99</option> 
        <option name="large" data-price="8.99">Large - £8.99</option> 
        <option name="e-large" data-price="9.99">Extra Large - £9.99</option> 
        <option name="f-size" data-price="10.99">Family Size - £10.99</option> 
       </select> 
       </span> 
      </form> 
     </fieldset> 
     <fieldset style = "border-top:0px"> 
     <form class="pure-form"> 
     <legend><b>Toppings (99p Each): &nbsp;</b></legend> 
     <input type="checkbox" name="onions">Onions</input> 
     <input type="checkbox" name="mushrooms">Mushrooms</input> 
     <input type="checkbox" name="peppers" >Peppers</input> 
     <input type="checkbox" name="olives" >Olives</input> 
     <input type="checkbox" name="garlic" >Garlic</input> 
     <input type="checkbox" name="peperoni" >Peperoni</input> 
     <input type="checkbox" name="cheese" >Pesto</input> 
     </form> 
     </fieldset> 
     <h2 id="cost" style= "float:left; margin-top:-3cm; margin-left: 9cm; border: solid black 2px; padding: 5px"> TEST </h2> 
     <br> 
    </div> 

JS:

$(document).on("change","#pizzaSize", function() { 
    $("input[type='checkbox']").prop('disabled', false); 
    var selectionPrice = $('option:selected', this).attr('data-price'); 
    var selectionInt = parseFloat(selectionPrice, 10); 
    pizzaCost = selectionInt; 
    $(this).closest('h2').text(pizzaCost); 
    calculateCost(pizzaCost, toppingCost, sideCost, drinkCost, desertCost, desertSizeCost, drinkSizeCost, sideSizeCost); 
}); 
+0

爲什麼不使用'$(「#cost」).text(pizzaCost)'? –

回答

1

closest()不只是工作得到您的控制字段集。如果你知道,H2來在同一水平上的字段集後,你可以這樣做:

$(this).closest('fieldset').nextAll('h2').first(); 

但是這取決於你的意思「最近」的東西。你可能想看看jQuery tree traversal functions

+0

h2我想插入文本到正好在代碼中的字段集下面。由於其他原因,我無法使用該ID,並且您的建議對我無效。 – SamG

+0

對不起,我沒有正確閱讀你的代碼。我更新了答案。現在它應該工作。 – lex82