[英]How can I rewrite this without using JQuery library just with JavaScript?
I have a couple of lines of code in JQuery: 我在JQuery中有几行代码:
var central = $('#townid option:contains("Central")');
if (central.length){
central.insertAfter('select option:first-child');
}
How can I rewrite it without using JQuery library just with JavaScript? 如何在不使用JavaScript的情况下使用JQuery库重写它?
A correct translation would be something like: 正确的翻译将是这样的:
var selects = document.getElementsByTagName('select'),
options = document.getElementById('townid').getElementsByTagName('option'),
options = Array.prototype.slice.call(options), //2 lines only for readability
tmp = document.createDocumentFragment();
for(var i = 0, l = options.length; i < l; i++) {
var option = options[i],
text = option.innerText || option.textContent;
if(text.indexOf('Central') > -1) {
tmp.appendChild(option);
}
}
for(var i = 0, l = selects.length; i < l; i++) {
var select = selects[i],
opts = select.getElementsByTagName('option');
if(opts.length > 1) {
select.insertBefore(tmp.cloneNode(true), opts[1]);
}
else {
select.appendChild(tmp.cloneNode(true));
}
}
This could be simplified a lot depending on the markup (and optimized depending on the browser (eg support for querySelectorAll
)). 这可以简化很多,具体取决于标记(并根据浏览器进行优化(例如支持
querySelectorAll
))。 Eg if you know that there will always only be one option that contains "Central" and whether there exists only one select
element or not. 例如,如果您知道将始终只有一个包含“Central”的选项以及是否只存在一个
select
元素。
Here is a stripped down version for one select
element, known size of the list (ie > 1) and only one option that contains Central
. 这是一个
select
元素的精简版本,列表的已知大小(即> 1),只有一个包含Central
选项。 So basically just reordering the option: 所以基本上只是重新排序选项:
var options = document.getElementById('townid').getElementsByTagName('option');
for (var i = 0, l = options.length; i < l; i++) {
var option = options[i],
text = option.innerText || option.textContent;
if (text.indexOf('Central') > -1) {
if (i > 1) {
option.parentNode.insertBefore(option, options[1]);
}
break;
}
}
Update: 更新:
If the option's text should be exactly Central
, compare the text normally: 如果选项的文本应该完全是
Central
,则通常比较文本:
if(text === 'Central')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.