简体   繁体   English

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

[英]Why does jQuery break this code?

When i use a jQuery id selector to select an element, it does not function the same as if i use plain JS.当我使用 jQuery id 选择器来选择一个元素时,它的功能与我使用普通 JS 的功能不同。 Why does the does the display block, or the src not change when using jQuery, but works with plain JS?为什么使用 jQuery 时显示块或 src 不会改变,但可以与纯 JS 一起使用?

See JS line 2 has working code comment that out and uncomment line 3 and select the element with the jQuery and it stops working.请参阅 JS 第 2 行已将工作代码注释掉并取消注释第 3 行并使用 jQuery 选择元素,然后它停止工作。

HTML 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 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 http://codepen.io/Zlerp/pen/xEqEAQ?editors=1010

Very simple.很简单。 When jQuery selects an element, it isn't the ELEMENT per se it's selecting, it's a jQuery object containing that element.当 jQuery 选择一个元素时,它所选择的并不是 ELEMENT 本身,而是一个包含该元素的 jQuery 对象。 If you do $("selector")[0], that will return the correct object.如果您执行 $("selector")[0],将返回正确的对象。 Or you can set style using the css function, eg $("selector").css("property","value").或者您可以使用 css 函数设置样式,例如 $("selector").css("property","value")。

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

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