jQuery 在这里面找到跨度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7150727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:28:12  来源:igfitidea点击:

finding span inside this

jquery

提问by scarhand

im trying to change the display attribute of a span inside of a li using the find function of jquery....its not working and i think i know why....because the span isnt inside of the input element right? but im not sure how to fix it

我正在尝试使用 jquery 的查找功能更改 li 内跨度的显示属性....它不起作用,我想我知道为什么....因为跨度不在输入元素内,对吗?但我不知道如何解决它

heres my code:

继承人我的代码:

$('form ul li input').click(function() {
    if ($(this).is(':checked'))
        $(this).find('span').attr('display', 'block');
    else
        $(this).find('span').attr('display', 'none');
});

i know all i need to do is make it so it searches the LI and not the INPUT....but im not sure how to do this.

我知道我需要做的就是让它搜索 LI 而不是 INPUT ....但我不知道如何做到这一点。

heres the HTML for an li:

下面是 li 的 HTML:

<li>

    <input type="checkbox" name="attack_strategies[]" id="strategy_4" value="4" /> 
    <label for="strategy_4">meditation</label>

    <span>

        <select name="attack_strategies_e[]" id="strategy_e_4">
        <option value="">How effective was it?</option>
        <option value="0">0</option>
        <option value="1">1</option><option value="2">2</option>
        <option value="3">3</option><option value="4">4</option>
        <option value="5">5</option><option value="6">6</option>
        <option value="7">7</option><option value="8">8</option>
        <option value="9">9</option><option value="10">10</option>          
        </select>

    </span>

</li>

回答by Felix Kling

You are right. Actually, an inputelement [HTML4 spec]cannot have any children:

你是对的。实际上,input元素[HTML4 规范]不能有任何子元素

<!ELEMENT INPUT - O EMPTY              -- form control -->

You can use closest[docs]to find the ancestor liand then search the spanfrom there:

您可以使用closest[docs]找到祖先li,然后span从那里搜索:

$(this).closest('li').find('span').css('display', 'block');

There might be other ways to to find the spanbut that depends on your HTML structure, which we don't know.

可能还有其他方法可以找到,span但这取决于您的 HTML 结构,我们不知道。

回答by diosney

In the code you posted, thisrefer to the input field, and .find()documentation reads:

在您发布的代码中,是指输入字段, .find()文档内容如下:

Description: Get the descendantsof each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

描述:获取当前匹配元素集合中每个元素的后代,通过选择器、jQuery 对象或元素过滤。

So you can't use find in an input field because it can haven't spanchild.

所以你不能在输入字段中使用 find ,因为它不能没有span孩子。

You can use what Felix Klingsuggests.

您可以使用Felix Kling 的建议。