【发布时间】:2017-12-03 14:18:29
【问题描述】:
我已经尝试了 StackOverflow 上的所有答案。但是,我似乎无法根据选项的值以编程方式选择选项。
我正在通过 Chrome 扩展程序中的内容脚本执行此操作 -> 不知道这是否会改变任何内容。
我的代码如下:
chrome.runtime.onMessage.addListener(
function(response, sender, sendResponse){
if (typeof response === 'string' || response instanceof String){
var dropdown = false;
if ((document.getElementById(response)).nodeName == 'SELECT'){
//console.log('im here');
dropdown = true;
var options = $('#' + response).find('option');
var random_num = ~~((Math.random() * (options.length - 1)) + 1 );
var radnom_option = options[random_num];
var value = radnom_option.value;
var slctr = ('#' + response);
/*
I thought that the next two lines would change the selected option.
*/
$(slctr).val(value);
$(slctr).trigger('change.select2');
console.log($(slctr));
console.log(options);
console.log(random_num);
console.log(radnom_option);
console.log(value);
console.log(slctr);
}
dropdown = true;
sendResponse(dropdown);
}
});
运行时,控制台显示:
[select#entity_email_1_createPersonEmailType.form-control.entity_email.select2.required, context: document, selector: "#entity_email_1_createPersonEmailType"]
[option, option#option_business, option#option_other, option#option_personal, option#option_school, prevObject: init[1], context: document, selector: "#entity_email_1_createPersonEmailType option"]
2
<option id="option_other" data-option-id="option_other" value="916">Other</option>
916
#entity_email_1_createPersonEmailType
我要修改的 HTML 部分是这样的:
<div
class="col-md-12"
>
<div class="form-group formGroup">
<label
class="control-label"
for="entity_email[1][quickAddPersonEmailType]"
>Email Type* </label>
<select
placeholder=""
class="form-control entity_email select2 required "
name="entity_email[1][email_type]"
id="entity_email_1_quickAddPersonEmailType"
title="Email Type"
data-field-suffix=""
data-field-name="email_type"
data-init-callback=""
data-field-alias="Email Type"
tabindex=""
data-field-required="entity_email" >
<option data-option-id="option_empty" value="">Select</option>
<option
id="option_business"
data-option-id="option_business"
value="915"
>Business</option>
<option
id="option_other"
data-option-id="option_other"
value="916"
>Other</option>
<option
id="option_personal"
data-option-id="option_personal"
value="913"
>Personal</option>
<option
id="option_school"
data-option-id="option_school"
value="914"
>School</option>
这就是我对控制台的期望。但是,选择元素仍然保留在第一个选项“选择”中。此外,当我尝试 StackOverflow 上概述的一种方法时,其中包括调用 select2() 函数,有一个 类型错误 说未定义 select2() 函数。但是,如果 HTML 包含 select2 元素,怎么会是这样呢?
我在这里做错了什么?是否有另一种方法可以实现能够选择特定选项的最终目标?例如,我可以删除所有选项,然后在更改默认值的同时重新添加它们吗?
任何帮助将不胜感激。提前致谢。
【问题讨论】:
标签: javascript jquery google-chrome-extension html-select