无法使用JavaScript选择最接近的h2元素

时间:2015-12-22 21:09:43

标签: javascript html

我希望能够选择最接近包含披萨选择选项的字段集的h2标题,并使用jQuery设置标题的文本。到目前为止我一直无法做到。

HTML:

Complexe::Complexe(const double re, const double im)
{
    double a = re;  //a is a local variable created in this stack frame
                    //content of re is copied inside a
    double b = im;

    this->re = &a;  //you are taking the address of a variable that is created on
                    // the stack and assigning it to a pointer that will persist
    this->im = &b;
} 
//when the constructor is finishes executing, a and b are destroyed,
//but this->re and this->im will continue to hold their address. 

JS:

   <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>

1 个答案:

答案 0 :(得分:1)

closest()仅适用于获取控件的字段集。如果您知道h2位于同一级别的字段集之后,您可以执行以下操作:

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

但这取决于你对'最接近'的意思。您可能想看一下jQuery tree traversal functions