开发者

jQuery selector vs. filter unexpected result

html is a piece of HTML containing inline Javascript resulting from an AJAX request. 开发者_运维知识库The following code:

$(html).filter('script')

returns a jQuery object for each script tag, whereas:

$('script', $(html))

returns an empty array. How is this possible? I'm using Chromium 10.0.


The difference is that $('script', $(html)) is turned into

$(html).find('script')

not

$(htmls).filter('script');

I believe that script tags of a certain type are removed from strings under the guise of keeping IE happy. A year ago, I delved into the jQuery source and found where it did that, but I can't remember why it did that.


Ok got something here, I wonder if answer is still relevant or not anyways here it goes.
Create a new JS file say it as "scriptTagTest.js" add the following js code

var html = '<div>I am DIV</div><script type="text/javascript">alert("I am inline");</script>';  
$(document).ready(function(e){  
  $('#inStr').text(html);  
});  

$('#test1').live('click', function(e){  
    var $html = $(html);  
  var o = $html.filter('script');  
  check(o);  
});  

$('#test2').live('click', function(e){  
    var $html = $(html);  
  var o = $('script', $html);  
  check(o);  
});  

function check($o, $html){  
  alert('obj len:'+ $o.length);  
    var $testArea = $('#testArea');  
  if($o.length > 0){  
    $testArea.append($o);  
  }  
  else{  
    $testArea.text('No script obj');  
  }  
}  

and then the html file as

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="scriptTagTest.js"></script>
</head>
<body>
  <p id="hello">Hello World</p>
  <div id="inStr">test</div>
  <button id="test1">Test $(html).filter('script')</button>
  <button id="test2">Test $('script', $(html))</button>
  <div id="testArea">&nbsp;</div>
</body>
</html>  

click "Test1" and "Test2" to see the results. Interestingly, the browser didn't parse the variable html with the <script> tag properly which I haven't come across earlier, thats why another JS file.

find() is used to look into the child elements while filter() finds in flat list of objects as well. If you incoming html is is in the form of the html variable then that might explain something.
Tested this in chrome 8 (desktop), FF, IE latest versions. Hope this helps. Best would be to drill down using Firebug!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜