我实际上正在使用 Jquery,并且在某些时候我使用 Jquery 选择器来使我的页面正常工作。这里的问题是,我使用的 HTML 可能会变得很长,具体取决于我使用的数据,它看起来像这样。
HTML
<div class="mailing"></div>
<input type="text" class="mail_subject"/>
<input type="text" class="mail_body"/> <!-- I can have 1 to n number of these -->
<!-- Preview tags -->
<p class='main_subject'></p>
<p class='main_body'></p>
<!--
And a few more things we don't use here
-->
</div>
<div id="table1">
<table id="ranking">
<tbody>
<!-- Data, can have 0 to ~3500 rows -->
</tbody>
</table>
</div>
如您所见,我的页面或多或少分为两部分,<div class="mailing">
,其中包含一些表单,以及 <div id="table1">
这是关于显示大量数据。
在我的邮件 div 中,我有一些输入和一个自动更新的预览,该预览从输入中获取数据。我这里拥有的是一种“邮件生成器”,其预览为我提供了 html 格式的结果。
这里的问题是关于性能的,我的 JQuery 被表格减慢了,当我输入表单时我出现了延迟,我不希望它搜索整个文档,因为我已经知道我的数据将在邮件中分区。
JS
$('.mailing').on('change click keyup keydown', function () {
// Here I append the mail_subject input to the preview
var text = $(this).val();
$('.main_subject').text($('.subject_select').val());
// Here I append each mail_body input to the preview
$('.bodies_select').each(function () {
text = $(this).val();
/*
* Some computation for the text
*/
jQuery('<span/>', {text: text}).appendTo('.main_body');
});
});
我还有一些类似这些的函数和更多的计算,但我认为我们已经了解了我的代码的样子。
我的问题是,当我使用像 $('.main_subject')
这样的 JQuery 选择器时,有什么办法吗?或$('.bodies_select')
不搜索整个 DOM 文档,而只在我的 mailing
中搜索例如div?问题是我可以将元素存储在变量中,因为它需要多次更新。
最佳答案
您可以将上下文与 jQuery 结合使用来提高性能:
$('.bodies_select', '.mailing')
您甚至可以使用一些技术来优化选择器:
关于javascript - JQuery选择器,部分DOM搜索表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43412734/