我正在进行A / B测试,对于变化的版本,我想跟踪Select2
下拉选项上的点击。
此特定选项是动态添加的,我认为这使事情变得复杂(我也在更改下拉菜单的占位符,但我认为这不会使事情变得混乱)。
在我的AB /测试平台上,我只能真正跟踪特定选择器的点击,因此,我试图找出可以选择该选项寄存器的任何方式。
很遗憾,我无法更改任何标记本身,但可以使用JavaScript/JQ
。
通常,如果我正在编写脚本,我只会从Select2
中检索选定的项目,但是在这种情况下,我只能使用可以跟踪点击的实际选择器。
我正在使用事件监听器来模拟和测试CSS选择器(JS代码的底部),但是没有运气。
$(document).ready(function() {
$('#dropdown').select2({
placeholder: "Old Placeholder",
minimumResultsForSearch: -1
});
var newOption = {
id: "01",
text: 'Dynamically Added Option',
value: "01"
};
var newOption = new Option(newOption.text, newOption.id, false, false);
$('#dropdown').append(newOption);
$('#dropdown').trigger('change.select2');
$('.select2-selection__placeholder').html('New Placeholder');
/******* HERE'S WHERE I'M TESTING SELECTORS FOR WHEN "DYNAMICALLY ADDED OPTION" IS SELECTED *******/
// track select2 list item with an id containing the new option's id
$('.select2-results__option[id*="01"]').on('click', function(){
alert("this never happens");
});
$('option[value="01"]').on('click', function(){
alert("this also never happens");
});
});
select {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<select id="dropdown">
<option></option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
答案 0 :(得分:0)
您可以为select添加更改事件,并对新元素进行小测试,例如:
$('#dropdown').on('change', function() {
if ($(this).val() === '01') {
console.log('The new option selected');
}
});
$(document).ready(function() {
$('#dropdown').select2({
placeholder: "Old Placeholder",
minimumResultsForSearch: -1
});
var newOption = {
id: "01",
text: 'Dynamically Added Option',
value: "01"
};
var newOption = new Option(newOption.text, newOption.id, false, false);
$('#dropdown').append(newOption);
$('#dropdown').trigger('change.select2');
$('.select2-selection__placeholder').html('New Placeholder');
// track select2 list item with an id containing the new option's id
$('#dropdown').on('change', function() {
if ($(this).val() === '01') {
console.log('The new option selected');
}
});
});
select {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<select id="dropdown">
<option></option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>