正确限制jQuery搜索范围?

时间:2015-05-06 17:20:12

标签: javascript jquery

我偶然发现了这段代码,我想知道它是否只是限制范围或同时选择这两个元素。

container = jQuery("#test", parent.document);

jQuery("param[name=scale]", another.object)

任何人都可以对此有所了解吗?

编辑:完整示例:

<script type="text/javascript">
jQuery = parent.jQuery;
container = jQuery("#test", parent.document);

another = {
    targetw: container.width()
};

function onEnd(){
  container.slideUp();
}

function onStart(){
  another.object = jQuery("object", document);

  another.w =  another.object.attr("width");
  another.h =  another.object.attr("height");
  another.targeth = Math.floor(another.targetw * another.h  / another.w);

  jQuery("div>iframe",container).width(another.targetw);
  jQuery("div>iframe",container).height(another.targeth);

  another.object.css("width", another.targetw+"px");
  another.object.css("height", another.targeth+"px");

  another.object.attr("width", another.targetw);
  another.object.attr("height", another.targeth);

  jQuery("param[name=scale]",another.object).attr("value","exactfit");

  another.object.parent().attr('style', function(i,s) { return s + 'background:none; width: '+another.targetw+'px !important; height: '+another.targeth+'px !important;' });

}
document.write('*snipped code*');
</script>

`

2 个答案:

答案 0 :(得分:5)

这似乎是jQuery选择器jQuery(selector[,context])的上下文参数。

来自http://api.jquery.com/jquery/

选择器上下文

默认情况下,选择器在DOM中从文档根开始执行搜索。但是,通过使用$()函数的可选第二个参数,可以为搜索提供备用上下文。例如,要在事件处理程序中进行搜索,可以限制搜索:

$( "div.foo" ).click(function() {
  $( "span", this ).addClass( "bar" );
});

当搜索范围选择器仅限于this的上下文时,只有单击元素中的跨度才会获得附加类。

在内部,选择器上下文使用.find()方法实现,因此$( "span", this )等同于$( this ).find( "span" )

答案 1 :(得分:2)

这是一个孩子 - 父选择器。搜索从父级而不是整个DOM开始。

$('childNode', parent)

相同
$(parent).find('childNode')

考虑container = jQuery("#test", parent.document);

由于#test是基于ID的选择器,因此jQuery('#test')不会产生任何差异,因为ID在DOM元素中是唯一的。