zz some JQeury code


1.get selected option in select:

 

Code

2.FAQ http://www.enpor.com/works/jquery-faq

内容

  * 1 怎样……?
  o 1.1 使用class或ID选择一个网页元素?
  o 1.2 测试一个元素是否有某个class属性?
  o 1.3 检查某个元素是否存在?
  o 1.4 How do I determine the state of a toggled element?
  o 1.5 How do I select an element that has weird characters in its ID?
  o 1.6 How do I disable/enable an element?
  o 1.7 How do I check/uncheck an input?
  o 1.8 How do I get the text value of a selected option?
  o 1.9 How do I replace text from the 3rd element of a list of 10 items?
  o 1.10 How do I compress my code?
  o 1.11 How do I submit a bug report?
  * 2 Why do … ?
  o 2.1 Why do my events stop working after an AJAX request?
  + 2.1.1 Re-binding
  + 2.1.2 Use Event Delegation
  o 2.2 Why doesn’t an event work on a new element I’ve created?
  o 2.3 Why do animations set the display style to block?
  * 3 When will…?
  o 3.1 When will jQuery 1.3 be released?
  o 3.2 When will jQuery UI 1.6 be released?
  * 4 Cookbook
  o 4.1 Recipe: Simple menu with hover to show sub-menu items
  o 4.2 Recipe: Hide All divs Except One
  o 4.3 Recipe: Multi-select Listbox without the Ctrl key


How do I … ?

How do I select an item using class or id?

  * This code selects an element with an id of “myDivId”. Since id’s are unique this expression always selects 1 element, or none if the id does not exist.

  $('#myDivId')

  * This code selects an element with a class of “myCssClass”. Since any number of elements can have the same class, this expression will select any number of elements.

  $('.myCssClass')

A selected element can be assigned to a javascript variable like this

  var myDivElement = $('#myDivId');

Usually selected elements are acted on by other JQuery functions:

  var myValue = $('#myDivId').val(); // get the value of an element

  $('#myDivId').val("hello world"); // set the value of an element

How do I test whether an element has a particular class?

(Sometimes also: Does jQuery have a hasClass method?)

  * You can use the is() method along with an appropriate selector

 if ( $('#myDiv').is('.pretty') )
  $('#myDiv').show();

Note that this method allows you to test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):

 if ( $('#myDiv').is(':hidden') )
  $('#myDiv').show();

  * Note also that hasClass has been added as of version 1.2 to handle the most common use of is():

$("div").click(function(){
  if ( $(this).hasClass("protected") )
  $(this)
  .animate({ left: -10 })
  .animate({ left: 10 })
  .animate({ left: -10 })
  .animate({ left: 10 })
  .animate({ left: 0 });
});

How do I test whether an element exists?

  * You can use the length property of the jQuery collection returned by your selector:

if ( $('#myDiv').length )
  $('#myDiv').show();

Note: It isn’t always necessary to test whether an element exists. The following code would show the item if it exists, and do nothing (no errors) if it did not:

$('#myDiv').show();

How do I determine the state of a toggled element?

You can check the state using the :visible or :hidden selectors.

 var isVisible = $('#myDiv').is(':visible');
 var isHidden = $('#myDiv').is(':hidden');

If you’re simply acting on an element based on its visibility, just include “:visible” or “:hidden” in the selector expression. For example:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');

How do I select an element that has weird characters in its ID?

For example, it can be common for some frameworks to generate unique IDs that have special characters in them (like ‘.’ or ‘[..]‘). The problem is that these characters have a special meaning in CSS.

Thankfully, jQuery has a workaround, which allows you to do the following:

 // Does not work
 $("#some.id")

 // Works!
 $("#some\\.id")

and another example:

 // Does not work
 $("#some[id]")

 // Works!
 $("#some\\[id\\]")

A convenient way to wrap some wrapping is the following function:

  function jq(myid)
  { return '#'+myid.replace(/:/g,"\\:").replace(/\./g,"\\.");}

this allows to use “just the ID” to identify a DOM-Element. jq(..) takes care of adding a ‘#’ at the beginning and escaping all dots.
How do I disable/enable an element?

You can disable/enable an element by setting the ‘disabled’ attribute to ‘disabled’ (to disable it) or “” (to enable it). The result of which looks something like this:

 // Disable #x
 $("#x").attr("disabled","disabled");
 // Enable #x
 $("#x").removeAttr("disabled");

You can try an example of enabling/disabling with the following demo:

and here’s the source code to the demo:

 <select id="x" style="width:200px;">
  <option>one</option>
  <option>two</option>

 </select>
 <input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
 <input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>

How do I check/uncheck an input?

You can check/uncheck an element by setting the ‘checked’ attribute to ‘checked’ (to check it) or “” (to uncheck it). The result of which looks something like this:

 // Check #x
 $("#c").attr("checked", "checked");
 // Uncheck #x
 $("#c").attr("checked","");

You can try an example of checking/unchecking with the following demo:

I’ll be checked/unchecked.

and here’s the source code to the demo:

 <label><input type="checkbox" id="c"/> I'll be checked/unchecked.</label>

 <input type="button" value="Check" onclick='$("#c").attr("checked","checked")'/>
 <input type="button" value="Uncheck" onclick='$("#c").attr("checked","")'/>

How do I get the text value of a selected option?

Select elements typically have two values that you want to access. First there’s the value, which is easy:

 $("select#myselect").val();
 // => 1

Next is getting the textual value of a select. For example, if you had the following select box:

 <select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>

  <option value="4">Dr</option>
  <option value="5">Prof</option>
 </select>

And you wanted to get the string “Mr” if the first option was selected (instead of just “1″). You would do that in the following way:

 $("#myselect option:selected").text();
 // => "Mr"

You can see this in action in the following demo:

and here’s the full source code to the demo:

 <select id="myselect">
  <option value="1">Mr</option>

  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>

 </select>
 <input type="button" value="Get Value" onclick="alert($('#myselect').val())"/>
 <input type="button" value="Get Text Value" onclick="alert($('#myselect option:selected').text())"/>

How do I replace text from the 3rd element of a list of 10 items?

Either the :eq() selector or the .eq() method will allow you to select the proper item. However, to replace the text, you must get the value before you set it:

  // This doesn't work
  $(this).find('li a').eq(2).text().replace('foo','bar');

  // This works
  var $thirdLink = $(this).find('li a').eq(2);
  var linkText = $thirdLink.text().replace('foo','bar');
  $thirdLink.text(linkText);

The first way only returns the string to you — the second way is required to actually replace it. Remember, .text() gets; .text(”foo”) sets. However, the trick here is that replace() is a JavaScript string method, not a jquery method. Thus, you have to return the string from the inner part, inside the outer part, in order to set its value.
How do I compress my code?

Generally the best way to do it is to use the YUI compressor.

An alternative is to use Douglas Crockford’s JSMin. This doesn’t compress JavaScript code as small, but generally how you write your code matters less. jQuery also provides a pre-minified version of jQuery for your convenience.

Packing javascript using Dean Edwards’ Packer (specifically using the base64 encode) is not recommended, as the client-side decoding has significant overhead that outweighs the file-size benefits.

If compressing your JavaScript breaks it, try running the code through JSLint. This will detect minor errors that can cause packed
JavaScript to fail where the unpacked version works fine.
How do I submit a bug report?

You can submit a bug report through the jQuery bug tracker.

Any information you can provide will help, such as:

  * A detailed bug report,
  * An online demo page, showing the problem,
  * A specific piece of code that is affected, or
  * A pointer to the area in jQuery where the bug occurs.

The more information a bug report has, the more likely it will be to get fixed. If a long period of time has gone by without an update to your bug, please bring it up for discussion on the jQuery Dev List.
Why do … ?

Why do my events stop working after an AJAX request?

Frequently, when you’ve added a click (or other event) handler to all links using $(’a').click(fn) you’ll find that the events no longer work after you’ve loaded new content into a page using an AJAX request.

When you call $(’a') it returns all the links on the page at the time and .click(fn) adds your handler to each individual element. When new links are added, they are unaffected. See the AJAX and Events Tutorial for longer discussion.

You have two ways of handling this:
Re-binding

This method implicates calling the method .bind() on the new added elements, as they are loaded/added. For example:

 $('a').click(fn);
 $('#mydiv').load('my.html',function(){
  $('a').click(fn);
 });

Beware not to bind on the same element/s over and over, or the function will be executed many times on each click (or any other event).

To learn more about event re-binding read this article on the Learning jQuery blog

Use the Live Query Plugin

Take a look at the Live Query plugin, by Brandon Aaron. It allows you to write something like this:

 $('a').livequery('click',fn);
 $('#mydiv').load('my.html');

The Live Query plugin automatically re-binds events to their target, even after you’ve loaded content in from a remote page.
Use Event Delegation

Event Delegation is a technique upheld by Event Bubbling. To handle events that bubble this way, you bind to a common container, and passively listen for events from there.

 $('#mydiv').click(function(e){
  if( $(e.target).is('a') )
  fn.call(e.target,e);
 });
 $('#mydiv').load('my.html');

Plugins for event delegation

Intercept, by Ariel Flesler, accepts any valid selector, and also a collection of selector/function.

 $('#mydiv').intercept('click', 'a', fn);
 $('#mydiv').load('my.html');

Listen, also by Ariel Flesler, can scale much better than its counterparts, it is able to handle large amounts of selectors with nearly no additional overhead. The downside is, that it only supports 4 kind of selectors.

 $('#mydiv').listen('click', 'a', fn);
 $('#mydiv').load('my.html');

If you want to read further: check out this great article by Karl Swedberg.
Why doesn’t an event work on a new element I’ve created?

As explained in the previous question about AJAX, events are bound only to elements that exist
when you issue the jQuery call. When you create a new element, you must rebind the event to it.

You can avoid this extra step by using the Live Query plugin, as explained in the previous question about Ajax.
Why do animations set the display style to block?

To start with, you need to remember that only block-style elements can have a custom width or height. When you do an animation on an element that animates the height or width (such as show, hide, slideUp, or slideDown) then the display style property will be set to ‘block’ for the duration of the animation. The display property will be reverted to its original value after the animation completes.

There are two common workarounds:

If you want to have the element stay inline, but you just want it to animate in or out, you can use the fadeIn or fadeOut animations - which only affect the opacity of an element (and thus, don’t need to have its display changed).

 // Instead of this:
 $("span").show("slow");

 // do this:
 $("span").fadeIn("slow");

The other option is to use a block-level element, but to add a float such that it appears to stay inline with the rest of the content around it. The result might looks something like this:

 // A floated block element
 <div style="float:left;">...</div>

 // Your code:
 $("div").show("slow");

When will…?

When will jQuery 1.3 be released?

Fall, 2008.
When will jQuery UI 1.6 be released?

jQuery UI v1.6 will be released in September, 2008.
Cookbook

<
Recipe: Simple menu with hover to show sub-menu items

  * See a simple show-submenu-on-hover-menu.

Recipe: Hide All divs Except One

  * See Hide All Except One (like tabs)
  o Simple markup, 13 lines, unobtrusive, bookmarkable.

Recipe: Multi-select Listbox without the Ctrl key

  * See Multiple select without the ctrl button

3.

获取一组radio被选中项的值
var item = $('input[@name=items][@checked]').val();
获取select被选中项的文本
var item = $("select[@name=items] option[@selected]").text();
select下拉框的第二个元素为当前选中值
$('#select_id')[0].selectedIndex = 1;
radio单选组的第二个元素为当前选中值
$('input[@name=items]').get(1).checked = true;
获取值:
文本框,文本区域:$("#txt").attr("value");
多选框checkbox:$("#checkbox_id").attr("value");
单选组radio: $("input[@type=radio][@checked]").val();
下拉框select: $('#sel').val();
控制表单元素:
文本框,文本区域:$("#txt").attr("value",'');//清空内容
$("#txt").attr("value",'11');//填充内容
多选框checkbox: $("#chk1").attr("checked",'');//不打勾
$("#chk2").attr("checked",true);//打勾
if($("#chk1").attr('checked')==undefined) //判断是否已经打勾
单选组radio: $("input[@type=radio]").attr("checked",'2');//设置value=2的项目为当前选中项
下拉框select: $("#sel").attr("value",'-sel3');//设置value=-sel3的项目为当前选中项
$("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel")//添加下拉框的option
$("#sel").empty();//清空下拉框
# //控制表单元素: //文本框,文本区域:
# $("#text_id").attr("value",'');//清空内容
# $("#text_id").attr("value",'test');//填充内容
# //多选框checkbox:
# $("#chk_id").attr("checked",'');//未选中的值
# $("#chk_id").attr("checked",true);//选中的值
# if($("#chk_id").attr('checked')==undefined) //判断是否已经选中
# //单选组radio:
# $("input[@type=radio]").attr("checked",'10');//设置value=10的单选按钮为当前选中项
# //下拉框select:
# $("#select_id").attr("value",'test');//设置value=test的项目为当前选中项
# $("<option value='test'>test</option><option value='test2'>test2</option>").appendTo("#select_id")//添加下拉框的 option
# $("#select_id").empty();//清空下拉框 


优质内容筛选与推荐>>
1、Unity 过度光照贴图
2、设置Cookies
3、XML的作用
4、socket 客户端-服务器的创建--day28
5、ural 2029 Towers of Hanoi Strike Back (数学找规律)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号