Как использовать colorbox для отображения скрытых элементов div на моей странице без жесткого кодирования? - PullRequest
14 голосов
/ 25 сентября 2010

Я использую Colorbox для отображения html-содержимого скрытых элементов div на моей странице. Я могу заставить это работать отлично со следующим:

$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});

Это покажет div с идентификатором 344.

Однако, поскольку я пытаюсь создать масштабируемую и динамическую страницу с помощью WordPress, я хочу иметь возможность захватывать идентификаторы моих элементов div с помощью функции, а не жестко кодировать их в вызове jquery.

Я изменил пример Джека Мура:

$("a[rel='example']").colorbox({title: function(){
    var url = $(this).attr('href');
    return '<a href="'+url+'" target="_blank">Open In New Window</a>';
}}); 

так, чтобы это выглядело так:

$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
    var elementID = $(this).attr('id');
    return elementID;
}}); 

Проблема в том, что свойство href функции colorbox ищет строку с знаком # перед идентификатором. Я пробовал различные способы конкатенации # в начале функции, включая # в возвращаемом значении и конкатенацию # в переменную elementID. Не повезло.

Я также попытался использовать синтаксис в примере Джека (без удачи), чтобы мое выражение return выглядело так:

return "#'+elementID+'";

Я думаю, что мой основной вопрос: как я могу использовать colorbox, чтобы показать скрытые элементы div на моей странице без жесткого кодирования всего?

Спасибо за вашу помощь, Jiert

Ответы [ 4 ]

7 голосов
/ 20 августа 2012

Мне не очень понравился ни один из ответов, приведенных выше.Вот как я это сделал (похоже, но не совсем так).Я также полностью прокомментировал это для людей, немного новичков в Javascript и плагине colorbox.

$(document).ready(function() { //waits until the DOM has finished loading
    if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
        $('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
            var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
            $(url).hide(); //hides the lightbox content div
            $(this).colorbox({
                 inline:true, // so it knows that it's looking for an internal href
                 href:url, // tells it which content to show
                 width:"70%",
                 onOpen:function(){ //triggers a callback when the lightbox opens
                    $(url).show(); //when the lightbox opens, show the content div
                 },
                 onCleanup:function(){
                    $(url).hide(); //hides the content div when the lightbox closes
                 }
            }).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
              //you could also use "return false" for the same effect but I proffered that way
        })
     }
});

И это HTML:

<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
     <p>Lightbox content goes here</p>
</div>

Я думаю, что это будет работать с несколькими лайтбоксамина одной странице, но я не проверял это с этим.

6 голосов
/ 28 сентября 2010

Я столкнулся с той же проблемой.Как выглядит ваш HTML?то есть, как вы структурировали свои "divs"

Моя выглядит так: Javascript:

<script>
    $(document).ready(function () {
    $("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
          var elementID = $(this).attr('id');
          return "#" + elementID;
       } 
      }); 
    });
</script>

И HTML выглядит так (я пытался изменить отображение: нет):

<a class='colorbox' href="#">Inline HTML</a>
   <div style="display:none">
       <div id="pop">
          This data is to be displayed in colorbox
       </div>
   </div>
4 голосов
/ 25 сентября 2010
return "#" + elementID; 

будет иметь желаемый эффект, как говорит Дэвид.

1 голос
/ 04 августа 2015

Вот так я и начал работать

HTML: (взято из примера в одном из ответов)

<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
     <p>Lightbox content goes here</p>
</div>

Javascript:

$('a.lightboxTrigger').click(function(){ 
    var ref = $(this).attr("href");
    $.colorbox({ html: $(ref).html() });
    $.colorbox.resize();
 });
...