选择td旁边的下一个选择框,然后按文本值选择一个选项

问题描述 投票:0回答:1

简而言之,我需要自动从webform中选择下拉值。我尝试过使用:

$("td:contains(Gender)")
    .closest('td')
    .next()
    .find('select')
    .filter(function () { return $(this).html() == "Female"; })
    .val();

(只是看看我是否可以返回任何内容并且表示未定义)

    $("td:contains(Gender)")
    .closest('td')
    .next()
    .find('select')
    .find('option:contains(Female)')
    .attr('selected', true)

(但这需要嵌套的find()才能工作

HTML看起来像:

<html>
<table>
    <tr>
        <td>Gender:</td>
        <td>
            <select>
                <option>Male</option>
                <option>Female</option>
            </select>
        </td>
    </tr>
</table>
</html>

缺点是由于构建webform的“独特”方式,我无法使用ID或类。我也知道我可能不能使用包含因男性和女性都包含“男性”。下拉列表中的值都是数值,所以我更喜欢我可以使用文本而不是映射值。

如果您想知道我是自动化工程师,那么我无法控制表单本身。

亲切的问候, ķ

javascript html jquery-select2
1个回答
2
投票

你几乎是正确的,你不需要调用.closest('td'),因为$("td:contains(Gender)")将返回td本身的jQuery对象。

$("td:contains(Gender)")
    .next()
    .find('select')
    .find('option:contains(Female)')
    .attr('selected', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<table>
    <tr>
        <td>Gender:</td>
        <td>
            <select>
                <option>Male</option>
                <option>Female</option>
            </select>
        </td>
    </tr>
</table>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.