How to pass a jQuery variable to a plugin property?
Sorry I'm beginner, can somebody help me out?
<script>
var iW = $(document).width();
$(function() {
//single book
$('#mybo开发者_如何学运维ok').booklet({
next: '#custom-next',
prev: '#custom-prev',
keyboard: true,
width: return iW, // here is the problem! It doesn't work.
height: 200
});
//multiple books with ID's
$('#mybook1, #mybook2').booklet();
//multiple books with a class
$('.mycustombooks').booklet();
});
</script>
You're really close. Just ditch the return
, e.g.:
$('#mybook').booklet({
next: '#custom-next',
prev: '#custom-prev',
keyboard: true,
width: iW, // <=== Updated
height: 200
});
That will use the value of iW
as of the time you call booklet
.
Within an object literal (that's the { ... }
thing that you're passing into the booklet
function), property initializers are a lot like assignment statements. The bit on the left before the :
gives the property name (and cannot be an expression), and the bit on the right after the :
gives the value for the property (and can be an expression — a simple variable name, a function call, etc.).
return
there is unnecessary. You just need width: iW
.
That said, you should also bring the call to $(document).width()
within the ready
block.
$(function () {
var iW = $(document).width();
//single book
$('#mybook').booklet({
next: '#custom-next',
prev: '#custom-prev',
keyboard: true,
width: iW,
height: 200
});
//multiple books with ID's
$('#mybook1, #mybook2').booklet();
//multiple books with a class
$('.mycustombooks').booklet();
});
As above, you don't need the return.
But alternatively many plugins will accept functions for their parameters to evaluate when needed so you could e.g.
$('#mybook').booklet({
next: '#custom-next',
prev: '#custom-prev',
keyboard: true,
width: function() { return $(document).width(); },
height: 200
});
I don't know that plugin so I'm not 100% sure it'll support it, but many do.
精彩评论