Ответ 1
return "#" + elementID;
будет иметь желаемый эффект, как говорит Дэвид.
Я использую Colorbox для отображения содержимого html скрытых div на моей странице. Я могу заставить это работать отлично со следующим:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
Это покажет div с идентификатором 344.
Однако, поскольку я пытаюсь создать масштабируемую и динамическую страницу с помощью WordPress, я хочу иметь возможность захватить идентификатор моих divs через функцию, а не жестко кодировать их в вызове 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 ищет строку С# знаком infront идентификатора. Я пробовал различные способы объединения # в начало функции, включая # в возвращаемом значении, и конкатенацию переменной # элемента. Не повезло.
Я также попытался использовать синтаксис в примере Джека (без везения), чтобы мой оператор return выглядел так:
return "#'+elementID+'";
Я думаю, что мой основной вопрос: как использовать colorbox для отображения скрытых div на моей странице без hardcoding?
Спасибо за вашу помощь, Jiert
return "#" + elementID;
будет иметь желаемый эффект, как говорит Дэвид.
Мне не понравился ни один из ответов, приведенных выше. Вот как я это сделал (похоже, но не совсем так). Я также полностью прокомментировал это для людей, немного новых для Javascript и plug-in 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 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 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>
Я думаю, что он будет работать с несколькими лайтбоксами на одной странице, но я не тестировал их с этим.
У меня такая же проблема. Как выглядит ваш 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 выглядит (я пытался изменить отображение: none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
Так я получил его на работу
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();
});