ric*_*oid 2 wordpress jquery selector jquery-lint
这是我的问题孩子:
jQuery(document).ready(function() {
var a = jQuery('img[title*="after"]');
a.parents('dl.gallery-item').addClass('after');
a.addClass('after');
var b = jQuery('img[title*="before"]');
b.parents('dl.gallery-item').addClass('before');
b.addClass('before');
//the following gives each image a 'name' attribute based on the caption, collapsed.
jQuery('img').each(function() {
var f = jQuery(this).parents('dl.gallery-item').find('dd').text();
var f = f.replace(/\s/g,'');
jQuery(this).attr('name', f);
});
//the following takes each 'name' attribute, finds the before, and sticks it behind the after
jQuery('img.after').hover(function() {
var imgName = jQuery(this).attr('name');
// alert(imgName);
var afterPosition_L = jQuery(this).offset().left;
var afterPosition_T = jQuery(this).offset().top;
var css_string = '{ top: '+ afterPosition_T +'; left: '+ afterPosition_L +'; position: absolute; z-index: 999;}';
var imgBefore = jQuery('img.before[name="'+ imgName +'"]');
// alert(imgBefore);
jQuery(imgBefore).css(css_string);
});
Run Code Online (Sandbox Code Playgroud)
说明:我正在使用WordPress(所以我拼写了jQuery).WordPress在图库中加载一堆图像(使用PHP).根据"标题"的一些字段和标题的内容,我确定它是"之前"还是"之后",并将该类分配给包装图像的标记,等等和img本身.我还根据标题文本为图像指定了"名称"属性.这一切都运作良好.
"悬停"是事情变得糟糕的地方.
当悬停没有任何反应时,鼠标输出会抛出Lint错误(在这篇文章的标题中).
应该发生什么:首先,我得到悬停图像的名称并将其粘贴在imgName中(这是有效的).接下来,我得到了悬停img的位置
这里的丑陋的东西:我尝试使用这个名字的变量从"本"与$识别图像("img.before [NAME ='’]"),即一个我们徘徊,并坚持在变量"imgBefore",然后我尝试将CSS应用于它,将其移动到与'after'相同的左/上位置,但使用不同的z-index.
'img.before [name =""]似乎是Lint抱怨的选择器......它说:
Selector: "img.before[name="CarterLivingRoom"]"
You've used the same selector more than once.
Run Code Online (Sandbox Code Playgroud)
所以它正确使用变量.它确实似乎在mouseout上抛出两次错误.也许'hover()'正在使用它两次,但是如何避免这种情况呢?
这里有很多问题.
document.ready函数将jQuery对象作为参数传递,因此您可以$在函数内部使用而不必担心碰撞.img.each,您重新定义var f多次.var在函数的顶部,每个函数使用一次通常被认为是好的形式; 这有助于您避免错误的重新声明.offset对象; 只需调用一次,然后使用结果对象的成员.self,所以你可以链接调用!这使您可以大量清理代码.imgBefore)中创建一个新的jQuery对象; 没必要那样做.此外,.css()可以采用对象而不是字符串,这使更新更容易/更清洁.重构:
jQuery(document).ready(function($) {
$('img[title*="after"]').addClass('after').
parents('dl.gallery-item').addClass('after');
$('img[title*="before"]').addClass('before').
parents('dl.gallery-item').addClass('before');
//the following gives each image a 'name' attribute based on the caption, collapsed.
$('img').each(function() {
var $this = $(this), f;
f = $this.parents('dl.gallery-item').find('dd').text().replace(/\s/g, '');
$this.attr('name', f);
});
//the following takes each 'name' attribute, finds the before, and sticks it behind the after
$('img.after').hover(function() {
var $this = $(this), offset = $this.offset();
$('img.before[name="' + $this.attr('name') + '"]').css({
top: offset.top,
left: offset.left,
position: 'absolute',
'z-index': 999
});
});
});
Run Code Online (Sandbox Code Playgroud)