這裏是用寫在POJS jQuery的替代。
HTML
<span id="CSSMLCall_call_outcome_types">
<input type="checkbox" name="CSSMLCall[call_outcome_types][]" value="5238" class="session_outcome_chk_list" id="CSSMLCall_call_outcome_types_0">
<label for="CSSMLCall_call_outcome_types_0">Client didn’t engage</label>
<input type="checkbox" name="CSSMLCall[call_outcome_types][]" value="4287" class="session_outcome_chk_list" id="CSSMLCall_call_outcome_types_1">
<label for="CSSMLCall_call_outcome_types_1">Complaint</label>
</span>
的Javascript
/*jslint maxerr: 50, indent: 4, browser: true */
/*global console, jQuery, $ */
(function() {
"use strict";
function walkTheDOM(node, func) {
if (node && node.nodeType) {
if (typeof func === "function") {
func(node);
}
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
}
function escapeRegex(string) {
return string.replace(/[\[\](){}?*+\^$\\.|]/g, "\\$&");
}
function filterElementsByContains(elements, string) {
var toStringFN = {}.toString,
text = toStringFN.call(elements),
result,
length,
i,
element;
if (text !== "[object NodeList]" && text !== "[object Array]" && !($() instanceof jQuery)) {
return result;
}
result = [];
if (typeof string === "string") {
string = new RegExp("^" + escapeRegex(string) + "$");
} else if (toStringFN.call(string) !== "[object RegExp]") {
return result;
}
function getText(node) {
if (node.nodeType === 3) {
text += node.nodeValue;
}
}
length = elements.length;
i = 0;
while (i < length) {
text = "";
element = elements[i];
walkTheDOM(element, getText);
if (string.test(text)) {
result.push(element);
}
i += 1;
}
return result;
}
function getAttribute(node, attribute) {
var undef;
if (!node || !node.nodeType || !attribute || typeof attribute !== "string" || !node.attributes || node.attributes[attribute] === undef) {
return undef;
}
return node.attributes[attribute].nodeValue;
}
var labels = document.getElementsByTagName("label");
console.log(getAttribute(filterElementsByContains(labels, "Complaint")[0], "for"));
console.log(filterElementsByContains(labels, "C"));
console.log(filterElementsByContains(labels, /C/));
console.log(filterElementsByContains(labels, /client/i));
console.log(filterElementsByContains(labels, "Client"));
console.log(filterElementsByContains($("label"), /Client/));
}());
輸出
CSSMLCall_call_outcome_types_1
[]
[label, label]
[label]
[]
[label]
在jsfiddle
有了這些功能,你可以提供一個NodeList
,Elements的Array
或參數的jQuery
對象。 string
參數可以是字符串或正則表達式。
它將返回一個過濾元素數組,其中包含與提供的字符串完全匹配的匹配正則表達式。
我相信這是比jquery :contains
選擇器更強大/靈活,它只能通過文本是否直接包含在所選元素中進行過濾。
這些功能應該是跨瀏覽器友好的,雖然我無法測試每個瀏覽器或每個可能的條件。
我也創建了一個jsperf,以便您可以比較jquery方法與此答案。
無論如何,我想我會與你分享這個選擇,而其他人也可能會覺得它有用。
感謝這一點。這很安靜,容易理解。 – dev1234