gpt4 book ai didi

javascript - 除了对每个元素进行函数调用之外,是否有更通用的方法在 HTML 元素上调用 JS 函数?

转载 作者:行者123 更新时间:2023-11-30 08:39:30 25 4
gpt4 key购买 nike

目前我像这样对每个元素进行函数调用:

<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)" />

是否有更通用/集中的方法来添加:

onblur="cleanWordClipboard(this)"

所有 TextArea 元素,所以

<textarea id="comment" cols=70 rows=5/>

保持原样。我在想像 CSS 这样的东西,它具有将行为应用于特定类型的所有元素的规则。

谢谢。

编辑1

到目前为止,我正在尝试,在我的页面底部,它实际上是一个包含所有动态页面(使用 ASP.NET MVC)的主布局页面:

            <script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
//return output;
input.value = output;
}
$('textarea').blur(cleanWordClipboard);
</script>

编辑2

       <textarea cols=10 rows=20 class="plaintextbox"></textarea>

<script language="JavaScript">

[].forEach.call(document.getElementsByClassName('plaintextbox'), function (element) {
element.addEventListener('blur', cleanWordClipboard);
// the element will be this in the cleanWordClipboard call
});

// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
//return output;
input.value = output;
}
</script>

最佳答案

是的,您可以在原生 JavaScript 中执行此操作:

[].forEach.call(document.getElementsByClassName('comment'), function(element){
element.addEventListener('blur', cleanWordClipboard);
// the element will be this in the cleanWordClipboard call
});

请注意,我假设您使用 class=comment 而不是 id=comment,因为文档中只有一个元素可以具有给定的 id。

关于javascript - 除了对每个元素进行函数调用之外,是否有更通用的方法在 HTML 元素上调用 JS 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27944164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com