10

我想选择存在于 DIV 中的一组特定按钮并将其 ID 分配给页面上的隐藏字段,但我无法终生选择 div 内的按钮。示例在下面失败

源 HTML

    <div id = test>
    <div class="ButtonGroupWrapper">                    
                    <img src="test.jpg" width="100" height="100" alt="thumbnail" />
                <input id="buttonID5" type="submit" value="Link" class="button" />
    </div>
    <div class="ButtonGroupWrapper">                    
                    <img src="test.jpg" width="100" height="100" alt="thumbnail" />
                <input id="buttonID6" type="submit" value="Link" class="button" />
    </div>
    </div>

Jquery 选择器失败

    $(".ButtonGroupWrapper").find(":button").click(function () {
        alert("hi there");
        return false;
    });

    $("#ButtonGroupWrapper input[type=button]").click(function () {
        alert("hi there");
        return false;
    });

    $("#ButtonGroupWrapper :button").click(function () {
        alert("hi there");
       return false;
    });
4

3 回答 3

15

尝试:

$(".ButtonGroupWrapper").find(".button").click(function () {
        alert("hi there");
        return false;
});

您的第一个示例失败,因为您试图定位一个以.not开头的类:。您可能还试图定位按钮类型的元素,但有问题的元素是提交类型。

您的第二个示例失败,因为您尝试在不存在时选择按钮类型的输入(您的目标是类型提交)。另一种选择是input[type=submit].

Your third example fails for a similar reason to the first example failing in that it's looking for an element of type button.

See also http://api.jquery.com/button-selector/

于 2012-08-08T19:30:30.110 回答
10

Putting a space looks for any .button class within your .ButtonGroupWrapper class. (NOTE: not any 'button', but anything with the code class="button" added to it)

$(".ButtonGroupWrapper .button").click(function () {
    alert("hello");
    return false;
});

In your HTML code the submit input has a 'class' of 'button'. It could actually be anything such as .strawberry or .mybutton or anything you like.

Alternative:

As you have an id wrapping the whole lot you could also target button within the id:

<div id ="test">
  <div>                    
    <img src="test.jpg" width="100" height="100" alt="thumbnail" />
    <input type="submit" value="Link" class="button" />
  </div>
  <div>                     
    <img src="test.jpg" width="100" height="100" alt="thumbnail" />
    <div class="button" />Just text</div>
  </div>
</div> 

And then your javascript could be:

$("#test .button").click(function () {
     alert("button class clicked");
    return false;
});

Remember you need to run this after the DOM has loaded, so best practice is to either write it at the end of the page or wrap it in your favourite onready function.

于 2014-05-15T16:43:52.310 回答
1

这将起作用:

$(".ButtonGroupWrapper").find(".button").click(function () {
    alert("hi there");
    return false;
});
于 2012-08-08T19:30:25.973 回答