我试图用jquery获取视频的宽度。
$(document).ready(function(){
$("#hp-video-player").bind("loadedmetadata", function () {
var vidWidth = this.videoWidth;
var vidHeight = this.videoHeight;
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
});
});
但是如果我尝试访问vadWidth& videHeight在函数之外
$(document).ready(function(){
$("#hp-video-player").bind("loadedmetadata", function () {
var vidWidth = this.videoWidth;
var vidHeight = this.videoHeight;
});
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
});
答案 0 :(得分:1)
在函数外声明变量。
$(document).ready(function(){
var vidHeight;
var vidWidth ;
$("#hp-video-player").bind("loadedmetadata", function () {
vidWidth = this.videoWidth;
vidHeight = this.videoHeight;
});
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
});
答案 1 :(得分:0)
try this ..vidWidth ,vidHeight local variables only visible inside function only
移动到该功能之外。
$(document).ready(function () {
var vidWidth, vidHeight;
$("#hp-video-player").bind("loadedmetadata", function () {
vidWidth = this.videoWidth;
vidHeight = this.videoHeight;
});
if (vidWidth != undefined) {
console.log('this is width ' + vidWidth);
}
if (vidHeight != undefined) {
console.log('this is height ' + vidHeight);
}
});
答案 2 :(得分:0)
您需要在函数外部声明变量,以使其范围更广。下面使变量范围在jQuery $()函数内,而不仅仅是bind函数。 值得研究变量范围。
$(document).ready(function(){
var vidWidth;
var vidHeight;
$("#hp-video-player").bind("loadedmetadata", function () {
vidWidth = this.videoWidth;
vidHeight = this.videoHeight;
});
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
});
答案 3 :(得分:0)
您可以全局声明变量,然后在控制台中打印,如下所示:
$(document).ready(function(){
var vidWidth = "";
var vidHeight = "";
$("#hp-video-player").bind("loadedmetadata", function () {
vidWidth = this.videoWidth;
vidHeight = this.videoHeight;
});
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
});
但是只有在为loadedmetadata
触发$("#hp-video-player")
事件后才会打印正确的值,在这种情况下,宽度和高度会在触发事件之前在控制台中打印。
但是如果你想在函数之外打印或使用正确的值,那么就这样做:
var vidWidth = "";
var vidHeight = "";
$(document).ready(function(){
$("#hp-video-player").bind("loadedmetadata", function () {
vidWidth = this.videoWidth;
vidHeight = this.videoHeight;
});
});
function printMetaData()
{
console.log('this is width ' + vidWidth);
console.log('this is height ' + vidHeight);
// you can do your desired task here.
}
答案 4 :(得分:0)
试试这个:声明一个全局对象。由于您正在观察loadedmetadata事件,因此将在此事件上分配值。您正在尝试在触发事件之前获取值的内容。你应该有一个活动" loadeddata"当值被赋予_dimension对象时应该触发。
var _dimension = { height : 0, width : 0 };
$(document).ready(function(){
$("#hp-video-player").bind("loadedmetadata", function () {
_dimension.width = this.videoWidth;
_dimension.height = this.videoWidth;
});
$("#hp-video-player").bind("loadeddata", function(){
console.log('this is width ' + _dimension.width);
console.log('this is height ' + _dimension.height);
});
});