$(this)在if($(" .element")中不起作用。是()

时间:2016-11-03 11:48:38

标签: javascript jquery

我对以下代码的预期结果为.csr-area-3 .csr-video,其中添加了csr-animate csr-zoom-in个类,为什么$(this)在这种情况下不起作用?

if ($(".csr-area-3 .csr-video").is(":in-viewport")) {
    $(this).addClass('csr-animate csr-zoom-in');
}

3 个答案:

答案 0 :(得分:7)

因为上下文是调用者函数/事件或可能是全局窗口上下文,所以再次使用相同的选择器以添加类:

if ($(".csr-area-3 .csr-video").is(":in-viewport")) {
    $(".csr-area-3 .csr-video").addClass('csr-animate csr-zoom-in');
}

根据评论进行修改

使用变量存储jquery查找的结果:

var csrvideo = $(".csr-area-3 .csr-video");
if (csrvideo.is(":in-viewport")) {
    csrvideo.addClass('csr-animate csr-zoom-in');
}

注意:使用过滤器作为@ saptal的答案将确保在存在多个元素的情况下将类添加到视口内的元素。

答案 1 :(得分:3)

您需要.filter(function),以获取匹配的元素,这些元素是视图中的端口,然后将类添加到

$(".csr-area-3 .csr-video").filter(function() {
    return $(this).is(":in-viewport");
}).addClass('csr-animate csr-zoom-in');

您也可以使用

$(".csr-area-3 .csr-video:in-viewport").addClass('csr-animate csr-zoom-in');

答案 2 :(得分:1)

如果您只使用

import os, re, fnmatch

directory_local = '/home/pi/testprogramme/python/' #Local upload directory
filename = 'lapfab.tgz'

# Capture the matching files.
file_pattern = "*%s" % filename
matches = sorted([local_filename for local_filename in os.listdir(directory_local) \
if fnmatch.fnmatch(local_filename, file_pattern)])

if len(matches) < 0:
    # Don’t process anything, no files
    return # or exit()

# Extract the variable
regex = r"([0-9]+)%s" % filename
match = re.search(regex, matches[0])

# Do something with the file.
print("Uploading job %s." % match.group(1))
full_path = os.path.join(directory_local,matches[0])

# Upload the file etc here.

$(this).someFunction(); 指的是this对象。

你需要做

window

(取决于你真正想要的)