如何使多个工作在这种情况下

How to make multiple working on this case

本文关键字:这种情况下 工作 何使多      更新时间:2023-09-26

Javascript

$(".show").change(function(){
    if ($(this).val() == "1") {    
        $(".text_area").show();
    }
    else {
        $(".text_area").hide();
    }
});

我想将此代码用于此类的所有元素,但是,当我选择对所有元素都有效的"值为1"的选项时。请帮忙。非常感谢。这里是演示点击这里

使用$(this).next():

$(".show").change(function () {
    if ($(this).val() == "1") {
        $(this).next(".text_area").show();
    } else {
        $(this).next(".text_area").hide();
    }
});

你必须使用关键字this$(this)在选择器的上下文事件中工作。

因为您有类名作为选择器,所以您应该注意它返回一个集合。这意味着,如果您有多个元素,那么它将引用所有元素,而this则引用应用于集合中当前选择器的事件。

如果您碰巧更改了html的顺序,例如将文本区域放在选择框之前,它将不起作用。因此,作为上一个答案的替代方案,您可以将您的组包装成div:

<div class="container">
    <select class="show">
        <option value="0">NO</option>
        <option value="1">YES</option>
    </select>
    <textarea class="form-control text_area" type="text" name="text_area" placeholder="Write something" rows="5" cols="50"></textarea>
</div>

当你要显示/隐藏文本区域时,你可以做:

$(this).closest('.container').find('.text_area').show();

$(this).closest('.container').find('.text_area').hide();

下面是一个演示:http://jsfiddle.net/n1fjo6qu/13/