为什么jQuery会破坏这段代码?

时间:2016-09-23 19:35:47

标签: javascript jquery html

当我使用jQuery id选择器来选择一个元素时,它的功能与使用普通JS的功能相同。为什么使用jQuery时显示块或src没有改变,但是使用普通的JS?

参见JS第2行有工作代码 注释掉并取消注释第3行并使用jQuery选择元素并停止工作。

HTML

<img id="myImg" src="https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" alt="Trolltunga, Norway" width="300" height="200">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">×</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

JS

// Get the modal
var modal = document.getElementById('myModal');
// var modal = $("#myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

http://codepen.io/Zlerp/pen/xEqEAQ?editors=1010

1 个答案:

答案 0 :(得分:3)

很简单。当jQuery选择一个元素时,它本身并不是ELEMENT选择的,它是一个包含该元素的jQuery对象。如果你执行$(&#34; selector&#34;)[0],那将返回正确的对象。或者您可以使用css函数设置样式,例如$(&#34;选择器&#34)。CSS(&#34;属性&#34;&#34;值&#34)。