Javascript(jquery),“jquery;指针;至';这';在另一个功能中?

Javascript(jquery),“jquery;指针;至';这';在另一个功能中?,javascript,jquery,Javascript,Jquery,大家好,谢谢回复:)。 我有这个模态图像库的代码 var $overlay = $("<div id='overlay'></div>"); var $image = $("<img class='overlayImage'>"); var $caption = $("<p></p>"); $overlay.append($image); $overlay.append($caption); $(".galle

大家好,谢谢回复:)。 我有这个模态图像库的代码

  var $overlay = $("<div id='overlay'></div>");
  var $image = $("<img class='overlayImage'>");
  var $caption = $("<p></p>");
  $overlay.append($image);
  $overlay.append($caption);

  $(".galleryWrap").append($overlay);
  $(".galleryItem").click(function(event) {
    event.preventDefault();
    var imageLocation = $(this).attr("href");
    $image.attr("src", imageLocation);
    $overlay.show();
    var captionText = $(this).children("img").attr("title");
    $caption.text(captionText);
      });
我是否可以将新的
imageLocation
变量指向在上一个函数中单击的
.galleryItem
,以获取下一个兄弟节点?
我知道这可能是另一种方式,只是玩和试着理解JS:)

为什么不简单地使用一个全局变量,您只需点击
.galleryItem
就可以将它分配给这个
?这将使全局变量成为单击的特定库项目。然后,您只需在第二个
单击
函数中检查此全局变量:

var selectedItem;
$(".galleryItem").click(function(event) {
  selectedItem = this; // selectedItem is now assigned to the specific .galleryItem
});
$overlay.click(function(event) {
  console.log(selectedItem); // Do something with selectedItem
});
这可以在以下示例中看到:

var-selectedItem;
$(“.galleryItem”)。单击(函数(事件){
selectedItem=this;//selectedItem现在已分配给特定的.galleryItem
});
$(“#覆盖”)。单击(函数(事件){
console.log(selectedItem);//使用selectedItem执行某些操作
});

一个
两个
三


覆盖
您可以在单击处理程序中移动显示逻辑,并使用全局变量来维护状态:

var $current = null;

$(".galleryItem").click(function(e) {
    e.preventDefault();
    $current = $(this);
    $overlay.show().click(); // trigger the click handler
});

$overlay.click(function(e) {
    e.preventDefault();
    var imageLocation = $current.attr("href");
    $image.attr("src", imageLocation);
    var captionText = $current.children("img").attr("title");
    $caption.text(captionText);

    $current = $current.next(); // point to next
    // ...etc
});

我想避免使用全局变量,因为它在JS中似乎有些不好的地方。所以在这个例子中,使用它的最佳方式是什么?非常感谢您的回答:)在JavaScript中使用全局变量唯一不好的地方是它会导致冲突。全局变量的好处是,它们在多个函数中具有相同的值,这正是您在这里想要的:)
var $current = null;

$(".galleryItem").click(function(e) {
    e.preventDefault();
    $current = $(this);
    $overlay.show().click(); // trigger the click handler
});

$overlay.click(function(e) {
    e.preventDefault();
    var imageLocation = $current.attr("href");
    $image.attr("src", imageLocation);
    var captionText = $current.children("img").attr("title");
    $caption.text(captionText);

    $current = $current.next(); // point to next
    // ...etc
});