[英]jQuery Issue: Running a function through each and picking up the element
所以我在通過.each運行函數時遇到問題,jQuery似乎沒有通過'this'來獲取有問題的元素。 下面的代碼:( 編輯:我試圖居中放置某些內容,而與多個元素的屏幕寬度完全無關)
$(document).ready(function(){
$('.main-feature h1').each(function() {
centerThis();
});
$('.meta-feature h2').each(function() {
centerThis();
});
});//doc-rdy
function centerThis(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
$(window).resize(function(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
});
}//centerThis
您應該this
作為參數傳遞給centerThis
函數:
$(document).ready(function(){
$('.main-feature h1').each(function() {
centerThis(this);
});
$('.meta-feature h2').each(function() {
centerThis(this);
});
});//doc-rdy
function centerThis(elem){
var trackHeight = $(elem).height()/2;
var trackWidth = $(elem).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(elem).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
$(window).resize(function(){
var trackHeight = $(this).height()/2;
var trackWidth = $(this).width()/2;
var pxInEmsHeight = Math.floor((trackHeight / 146) * 100) / 100;
var pxInEmsWidth = Math.floor((trackWidth / 146) * 100) / 100;
$(this).css({
"margin-left": -pxInEmsWidth+'em',
"margin-top": -pxInEmsHeight+'em'
});
});
}//centerThis
您必須將其作為參數提供給要調用的函數centerThis(),並將函數中的$(this)替換為輸入參數的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.