Как использовать обычный javaScript для обхода домена, замены изображения, замены функции jQuery - PullRequest
0 голосов
/ 03 февраля 2020

Итак, я преобразую эту функцию из jQuery в обычную javascript и использую преимущество querySelectorAll

Вот мое примечание HTML *, будет несколько таких carBox, повторяющихся html template

<div class="carBox">
<p class="carHead">Porsche 997 GT3</p>
<div>
    <p><img alt="Porsche 997 GT3" height="600" src="img/a.jpg" width="800" /></p>
</div>
<div>
    <p><img alt="Porsche 997 GT3" height="600" src="img/a.jpg" width="800" /></p>
    <p><img alt="Porsche 997 GT3" height="600" src="img/b.jpg" width="800" /></p>
    <p><img alt="Porsche 997 GT3" height="600" src="img/c.jpg" width="800" /></p>
    <p><img alt="Porsche 987 GT3" height="450" src="img/d.jpg" width="800" /></p>
</div>
<p class="carInfo">The Porsche 911 GT3 is a high performance version of the Porsche 911 sports car primarily intended for racing. It is a line of high-performance models, which began with the 1973 911 Carrera RS.</p>

И моя jquery

$(document).ready(function(){
    $('.carBox div:nth-of-type(2) p img').hover(function(){
        var src = $(this).attr('src');
        $(this).parent().parent().prev().children().children().attr('src',src);
    })
});

обычная javascript версия, это правильный путь?

var subImg = document.querySelectorAll('.carBox div:nth-of-type(2) p img');
function swap(){
    this.parentNode.parentNode.previousElementSibling.children[0].children[0].src = this.src;
}
for(var i = 0; i < subImg.length; i++){
    subImg[i].addEventListener('mouseover',swap,false);
};

Вот пример того, как это выглядит в производстве

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...