简体   繁体   English

有关性能jQuery的问题

[英]Questions about performance jQuery

I had a question about performance ? 我对性能有疑问吗?

Is it better to have the two images written in html, one hidden and one displayed, and with jQuery change the display of both (to hide the one displayed, and show the hided one) ? 最好用html编写两个图像,一个隐藏并显示一个,用jQuery更改两个图像的显示(隐藏一个显示,并显示一个隐藏)?

<img id="1" style="display:none;" src="img1.png" />
<img id="2" src="img2.png" />
$('#1').onclick(function (){
  $(this).css('display', 'none');
  $("#2").css('display', 'inline-block');
});
$('#2').onclick(function (){
  $(this).css('display', 'none');
  $("#1").css('display', 'inline-block');
});

or is it better to change the src of the image ? 还是更改图像的src更好?

$('#1').onclick(function (){
  if ($(this).attr('src') == 'img1.png')
    $(this).attr('src', 'img2.png');
  else
    $(this).attr('src', 'img1.png');
});

Thank you very much! 非常感谢你!

Replacing the src is probably a better approach since the image request will be made on demand (if the click event was triggered) if the user does not click it, then you save one unnecessary request. 替换src可能是一种更好的方法,因为如果用户未单击图像请求(如果触发了click事件),则会按需发出图像请求,那么您可以保存一个不必要的请求。

However, if the image needs to be changed multiple times with clicks this can be a lot of unnecessary requests. 但是,如果需要通过单击多次更改图像,则可能会有很多不必要的请求。

An alternative would be is to create 2 images in the DOM and swap based on the click 一种替代方法是在DOM中创建2张图片,然后根据点击次数进行交换

var $img1 = $('<img>', {
    src: 'img1.png'
});
var $img2 = $('<img>', {
    src: 'img2.png'
});


$('#1').click(function (){
  if ($(this).attr('src') == 'img1.png')
    $(this).html($img2);
  else
    $(this).html($img1);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM