gpt4 book ai didi

javascript - 如何根据文本变量选择 MultipleChoice 选项

转载 作者:行者123 更新时间:2023-12-03 03:56:10 25 4
gpt4 key购买 nike

我有一个 MultipleChoiceField 和一个变量 my_choice = 'mystring'

我想检查与my_choice相关的选项

这是我的html:

    ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>

这里是我的javascript:

var my_choice = 'mystring'
var opt = $("#id_layer_select option");
opt.filter("[value=my_choice]").attr("selected", true);

我可以使用jquery。谢谢

PS:当然mystring是一个选项Mychoice1Mychoice2或等等。

我不想使用 id_layer_select_x 并且我不想添加 和 属性。

问题是该复选框未选中并且

console.log(opt)=Object { length: 0, prevObject: Object[1] }

最佳答案

您可以按跨度包含的文本过滤所有跨度。然后,您可以获取前一个元素并对其进行检查。

$(document).ready(function() {
var txt = "Mychoice3";


var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) {
return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection.
}).prev().prop('checked', true);
});
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>

<body>

<ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
</body>

关于javascript - 如何根据文本变量选择 MultipleChoice 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44936986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com