提问人:Bphanendrak 提问时间:9/12/2023 最后编辑:Peter MortensenBphanendrak 更新时间:9/16/2023 访问量:65
JavaScript 解析错误给出错误的输出,不考虑文本是否在下一行中
JavaScript parsing error giving the wrong output, not considering if text is in the next line
问:
考虑:
document.addEventListener("DOMContentLoaded", function () {
const checkButton = document.getElementById("checkButton");
const resultDiv = document.getElementById("result");
checkButton.addEventListener("click", function () {
const htmlCode = document.getElementById("htmlInput").value;
// Split the HTML code into lines for line number tracking
const lines = htmlCode.split('\n');
// Regular expression pattern to match <a> tags with alias attributes
const aTagPattern = /<a[^>]*alias="([^"]*)"/g;
const aliasMatches = [];
// Initialize arrays to store errors and warnings along with line numbers
const invalidAliases = [];
const missingAliases = [];
// Loop through each line and check for <a> tags with alias attributes
lines.forEach((line, lineNumber) => {
const aTagMatches = [...line.matchAll(aTagPattern)];
aTagMatches.forEach((match) => {
const alias = match[1];
if (!/^[a-zA-Z0-9_]+$/.test(alias)) {
invalidAliases.push(`Invalid alias "${alias}" on line ${lineNumber + 1}`);
}
});
if (!line.includes('alias=')) {
const hrefMatch = line.match(/<a[^>]*href="([^"]+)"/);
if (hrefMatch) {
const href = hrefMatch[1];
missingAliases.push(`Missing alias for href="${href}" on line ${lineNumber + 1}`);
}
}
});
// Generate result messages
let resultMessage = "";
if (missingAliases.length > 0) {
resultMessage += "Missing Aliases:\n" + missingAliases.join('\n') + "\n";
}
if (invalidAliases.length > 0) {
resultMessage += "Invalid Aliases:\n" + invalidAliases.join('\n') + "\n";
} else if (missingAliases.length === 0) {
resultMessage = "All aliases are in the correct format.";
}
// Display the result message
if (resultMessage !== "") {
resultDiv.innerText = resultMessage;
} else {
resultDiv.innerText = "HTML code is valid!";
}
});
});
这是我的 JavaScript 代码。主要功能是检查别名属性,如果缺少别名,则会给出错误或格式不正确。
它采用 HTML 代码作为输入。它工作正常,但如果别名在下一行,则不会认为它给出没有找到别名错误。我该如何解决?
如果别名在同一行中,则正确的输出:
如果下一行中的别名,则输出错误:
答:
0赞
ControlAltDel
9/12/2023
#1
你可以使用
var withAlias = document.querySelectorAll("a[alias]");
获取具有 alias 属性的所有锚标记。使用它,您可以执行以下操作
withAlias.forEach(function(aTag) {
// run your regex on aTag.getAttribute("[alias]");
// to determine correctness
});
要获取所有没有别名属性的锚标记,您可以执行以下操作
var noAlias = document.querySelectorAll("a:not([alias])");
大多数人都会同意,这样更容易看到你在做什么
评论
0赞
This Guy
9/12/2023
这是使用 css 选择器的一个惊人示例。干的好!
0赞
mplungjan
9/12/2023
链接不在文档中
0赞
This Guy
9/12/2023
#2
使用内置的选择器和 getAttribute,您可以遍历元素并检查是否存在别名属性。
UPDATE:现在使用文本输入字段,并在单击按钮时复制到隐藏元素进行评估。
function consider(ctxt) {
let links = ctxt.querySelectorAll('a');
console.table(links);
links.forEach(l => {
let alias = l.getAttribute('alias');
if (alias == null) {
console.log(l.innerText + ' does not have alias');
} else {
console.log(l.innerText + ' alias is ' + alias);
}
})
}
//set initial textbox value
document.getElementById('textField').value = '<a href="www.test.net" alias="test.net">Testing</a><br/><a href="www.e2d2.ca">Dont go here!</a>';
//mockup and connect button
document.getElementById('consider').addEventListener('click', (e)=>{
// copy to context, load
let ctxt = document.getElementById('ctxt');
ctxt.innerHTML = "";
ctxt.innerHTML = document.getElementById('textField').value;
//evaluate against the context element
consider(ctxt);
});
<textarea id="textField" type="text"></textarea><button id="consider">Evaluate</button>
<context id="ctxt" style="display:none"></>
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
评论
0赞
mplungjan
9/12/2023
链接不在文档中
0赞
This Guy
9/12/2023
好吧,这可能会导致一些问题哈哈
1赞
mplungjan
9/16/2023
此外,您可能不想调用函数 eval,因为已经有一个 window.eval 也不受欢迎
0赞
mplungjan
9/12/2023
#3
您可以使用片段来简化此操作。请不要使用正则表达式
document.addEventListener("DOMContentLoaded", function() {
const checkButton = document.getElementById("checkButton");
const resultDiv = document.getElementById("result");
checkButton.addEventListener("click", function() {
const htmlCode = document.getElementById("htmlInput").value;
const fragment = document.createElement("div");
fragment.innerHTML = htmlCode;
const aliasMatches = fragment.querySelectorAll("a[alias]");
// Initialize arrays to store errors and warnings along with line numbers
const invalidAliases = ["Invalid Aliases:"];
const missingAliases = ["Missing Aliases:"];
const noAliasMatches = fragment.querySelectorAll("a:not([alias])");
if (noAliasMatches.length > 0) noAliasMatches
.forEach((match, i) => missingAliases.push(`Missing alias for with href = "${match.href}"`));
// Loop through each line and check for <a> tags with alias attributes
aliasMatches.forEach((match, i) => {
const alias = match.getAttribute("alias");
if (alias === "") {
missingAliases.push(`Empty alias for link with href = "${match.href}"`);
} else if (!/^[a-zA-Z0-9_]+$/.test(alias)) {
invalidAliases.push(`Invalid alias "${alias} for link with href = "${match.href}"`);
}
});
// Generate result messages
let resultMessage = [];
if (missingAliases.length > 1) resultMessage = resultMessage.concat(missingAliases);
if (invalidAliases.length > 1) resultMessage = resultMessage.concat(invalidAliases);
if (resultMessage.length === 0) resultMessage = ["All aliases are in the correct format."];
resultDiv.innerHTML = resultMessage.join("<br/>");
});
});
<textarea id="htmlInput"><a href="bla"
alias="Hello"
>Visit bla</a>
<a href="bla1"
alias=""
>Visit bla1</a>
<a href="bla2"
>Visit bla2</a>
</textarea>
<button type="button" id="checkButton">Check</button>
<div id="result"></div>
评论
1赞
Bphanendrak
9/16/2023
谢谢,mplungjan!它确实解决了问题。
评论