'Language/jQuery'에 해당되는 글 29건

  1. 2014.11.17 jQuery Colorbox
  2. 2014.11.17 jQuery Validation Plugin
  3. 2014.11.17 jQuery Simulate
  4. 2014.11.17 https://code.google.com/p/jqueryjs/
  5. 2013.02.19 find, filter, children
  6. 2013.02.14 jquery masked plugin
  7. 2011.01.05 .get
  8. 2010.10.25 jQuery.each(object, callback function)
  9. 2010.10.25 Selectors

jQuery Colorbox

Language/jQuery 2014. 11. 17. 15:08

Colorbox - a jQuery lightbox

A lightweight customizable lightbox plugin for jQuery


view demo

1 2 3 4 5

Download

Released under the MIT License. Source on Github (changelog).
Compatible with: jQuery 1.3.2+ in Firefox, Safari, Chrome, Opera, Internet Explorer 7+
Bower Package: jquery-colorbox

 

  • Supports photos, grouping, slideshow, ajax, inline, and iframed content.
  • Lightweight: 10KB of JavaScript (less than 5KBs gzipped).
  • Appearance is controlled through CSS so it can be restyled.
  • Can be extended with callbacks & event-hooks without altering the source files.
  • Completely unobtrusive, options are set in the JS and require no changes to existing HTML.
  • Preloads upcoming images in a photo group.
  • Currently used on more than 1.9 million websites.

Instructions & Help

The FAQ has instructions on asking for help, solutions to common problems, and how-to examples. First-time jQuery users can check out the Colorbox Beginner's Guide. Intermediate users can probably glean everything needed by view-source'ing the demo pages.

Usage

Colorbox accepts settings from an object of key/value pairs, and can be assigned to any HTML element.

// Format:
$(selector).colorbox({key:value, key:value, key:value});
// Examples:
// Image links displayed as a group
$('a.gallery').colorbox({rel:'gal'});

// Ajax
$('a#login').colorbox();

// Called directly, without assignment to an element:
$.colorbox({href:"thankyou.html"});

// Called directly with HTML
$.colorbox({html:"<h1>Welcome</h1>"});

// Colorbox can accept a function in place of a static value:
$("a.gallery").colorbox({rel: 'gal', title: function(){
  var url = $(this).attr('href');
  return '<a href="' + url + '" target="_blank">Open In New Window</a>';
}});

Settings

PropertyDefaultDescription
transition"elastic"The transition type. Can be set to "elastic", "fade", or "none".
speed350Sets the speed of the fade and elastic transitions, in milliseconds.
hreffalseThis can be used as an alternative anchor URL or to associate a URL for non-anchor elements such as images or form buttons. $("h1").colorbox({href:"welcome.html"});
titlefalseThis can be used as an anchor title alternative for Colorbox.
relfalseThis can be used as an anchor rel alternative for Colorbox. This allows the user to group any combination of elements together for a gallery, or to override an existing rel so elements are not grouped together. $("a.gallery").colorbox({rel:"group1"}); Note: The value can also be set to 'nofollow' to disable grouping.
scalePhotostrueIf true, and if maxWidth, maxHeight, innerWidth, innerHeight, width, or height have been defined, Colorbox will scale photos to fit within the those values.
scrollingtrueIf false, Colorbox will hide scrollbars for overflowing content. This could be used on conjunction with the resize method (see below) for a smoother transition if you are appending content to an already open instance of Colorbox.
opacity0.85The overlay opacity level. Range: 0 to 1.
openfalseIf true, Colorbox will immediately open.
returnFocustrueIf true, focus will be returned when Colorbox exits to the element it was launched from.
trapFocustrueIf true, keyboard focus will be limited to Colorbox's navigation and content.
fastIframetrueIf false, the loading graphic removal and onComplete event will be delayed until iframe's content has completely loaded.
preloadingtrueAllows for preloading of 'Next' and 'Previous' content in a group, after the current content has finished loading. Set to false to disable.
overlayClosetrueIf false, disables closing Colorbox by clicking on the background overlay.
escKeytrueIf false, will disable closing colorbox on 'esc' key press.
arrowKeytrueIf false, will disable the left and right arrow keys from navigating between the items in a group.
looptrueIf false, will disable the ability to loop back to the beginning of the group when on the last element.
datafalseFor submitting GET or POST values through an ajax request. The data property will act exactly like jQuery's .load() data argument, as Colorbox uses .load() for ajax handling.
classNamefalseAdds a given class to colorbox and the overlay.
fadeOut300Sets the fadeOut speed, in milliseconds, when closing Colorbox.
closeButtontrueSet to false to remove the close button.
Internationalization
current"image {current} of {total}"Text or HTML for the group counter while viewing a group. {current} and {total} are detected and replaced with actual numbers while Colorbox runs.
previous"previous"Text or HTML for the previous button while viewing a group.
next"next"Text or HTML for the next button while viewing a group.
close"close"Text or HTML for the close button. The 'esc' key will also close Colorbox.
xhrError"This content failed to load."Error message given when ajax content for a given URL cannot be loaded.
imgError"This image failed to load."Error message given when a link to an image fails to load.
Content Type
iframefalseIf true, specifies that content should be displayed in an iFrame.
inlinefalse

If true, content from the current document can be displayed by passing the href property a jQuery selector, or jQuery object.

// Using a selector:
$("#inline").colorbox({inline:true, href:"#myForm"});

// Using a jQuery object:
var $form = $("#myForm");
$("#inline").colorbox({inline:true, href:$form});
htmlfalseFor displaying a string of HTML or text: $.colorbox({html:"<p>Hello</p>"});
photofalseIf true, this setting forces Colorbox to display a link as a photo. Use this when automatic photo detection fails (such as using a url like 'photo.php' instead of 'photo.jpg')
ajaxThis property isn't actually used as Colorbox assumes all hrefs should be treated as either ajax or photos, unless one of the other content types were specified.
Dimensions
widthfalseSet a fixed total width. This includes borders and buttons. Example: "100%", "500px", or 500
heightfalseSet a fixed total height. This includes borders and buttons. Example: "100%", "500px", or 500
innerWidthfalseThis is an alternative to 'width' used to set a fixed inner width. This excludes borders and buttons. Example: "50%", "500px", or 500
innerHeightfalseThis is an alternative to 'height' used to set a fixed inner height. This excludes borders and buttons. Example: "50%", "500px", or 500
initialWidth300Set the initial width, prior to any content being loaded.
initialHeight100Set the initial height, prior to any content being loaded.
maxWidthfalseSet a maximum width for loaded content. Example: "100%", 500, "500px"
maxHeightfalseSet a maximum height for loaded content. Example: "100%", 500, "500px"
Slideshow
slideshowfalseIf true, adds an automatic slideshow to a content group / gallery.
slideshowSpeed2500Sets the speed of the slideshow, in milliseconds.
slideshowAutotrueIf true, the slideshow will automatically start to play.
slideshowStart"start slideshow"Text for the slideshow start button.
slideshowStop"stop slideshow"Text for the slideshow stop button
Positioning
fixedfalseIf true, Colorbox will be displayed in a fixed position within the visitor's viewport. This is unlike the default absolute positioning relative to the document.
topfalseAccepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport.
bottomfalseAccepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport.
leftfalseAccepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport.
rightfalseAccepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport.
repositiontrueRepositions Colorbox if the window's resize event is fired.
Retina Images
retinaImagefalseIf true, Colorbox will scale down the current photo to match the screen's pixel ratio
retinaUrlfalseIf true and the device has a high resolution display, Colorbox will replace the current photo's file extention with the retinaSuffix+extension
retinaSuffix"@2x.$1"If retinaUrl is true and the device has a high resolution display, the href value will have it's extention extended with this suffix. For example, the default value would change my-photo.jpg to my-photo@2x.jpg
Callbacks
onOpenfalseCallback that fires right before Colorbox begins to open.
onLoadfalseCallback that fires right before attempting to load the target content.
onCompletefalseCallback that fires right after loaded content is displayed.
onCleanupfalseCallback that fires at the start of the close process.
onClosedfalseCallback that fires once Colorbox is closed.

Public Methods

$.colorbox()This method allows you to call Colorbox without having to assign it to an element. $.colorbox({href:"login.php"});
$.colorbox.next()
$.colorbox.prev()
These methods moves to the next and previous items in a group and are the same as pressing the 'next' or 'previous' buttons.
$.colorbox.close()This method initiates the close sequence, which does not immediately complete. The lightbox will be completely closed only when the cbox_closedevent / onClosed callback is fired.
$.colorbox.element()This method is used to fetch the current HTML element that Colorbox is associated with. Returns a jQuery object containing the element. var $element = $.colorbox.element();
$.colorbox.resize()This allows Colorbox to be resized based on it's own auto-calculations, or to a specific size. This must be called manually after Colorbox's content has loaded. The optional parameters object can accept width or innerWidth and height orinnerHeight. Without specifying a width or height, Colorbox will attempt to recalculate the height of it's current content.
$.colorbox.remove()Removes all traces of Colorbox from the document. Not the same as $.colorbox.close(), which tucks colorbox away for future use.

Event Hooks

These event hooks fire at the same time as their corresponding callbacks (ie. cbox_complete & onComplete), but can be used to make a universal change to Colorbox, while callbacks are only applied to selected elements.

// Example of using an event listener and public method to build a primitive slideshow:
$(document).bind('cbox_complete', function(){
  setTimeout($.colorbox.next, 1500);
});
cbox_opentriggers when Colorbox is first opened, but after a few key variable assignments take place.
cbox_loadtriggers at the start of the phase where content type is determined and loaded.
cbox_completetriggers when the transition has completed and the newly loaded content has been revealed.
cbox_cleanuptriggers as the close method begins.
cbox_closedtriggers as the close method ends.



출처 - http://www.jacklmoore.com/colorbox/

'Language > jQuery' 카테고리의 다른 글

JQuery Validation(Validate) Plugin  (0) 2014.11.17
jQuery Notification  (0) 2014.11.17
jQuery Validation Plugin  (0) 2014.11.17
jQuery Simulate  (0) 2014.11.17
https://code.google.com/p/jqueryjs/  (0) 2014.11.17
:

jQuery Validation Plugin

Language/jQuery 2014. 11. 17. 15:05

Documentation

Validate forms like you've never validated before!

"But doesn't jQuery make it easy to write your own validation plugin?"
Sure, but there are still a lot of subtleties to take care of: You need a standard library of validation methods (such as emails, URLs, credit card numbers). You need to place error messages in the DOM and show and hide them when appropriate. You want to react to more than just a submit event, like keyup and blur.
You may need different ways to specify validation rules according to the server-side enviroment you are using on different projects. And after all, you don't want to reinvent the wheel, do you?

"But aren't there already a ton of validation plugins out there?"
Right, there are a lot of non-jQuery-based solutions (which you'd avoid since you found jQuery) and some jQuery-based solutions. This particular one is one of the oldest jQuery plugins (started in July 2006) and has proved itself in projects all around the world. There is also anarticle discussing how this plugin fits the bill of the should-be validation solution.

Not convinced? Have a look at this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required/>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required/>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url"/>
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>

Isn't that nice and easy?

A single line of jQuery to select the form and apply the validation plugin, plus a few annotations on each element to specify the validation rules.

Of course that isn't the only way to specify rules. You also don't have to rely on those default messages, but they come in handy when starting to setup validation for a form.

A few things to look out for when playing around with the demo

  • After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field. If another invalid field – that wasn't the first one – was focused before submit, that field is focused instead, allowing the user to start at the bottom if he or she prefers.
  • Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value
  • Once a field is marked invalid, it is eagerly validated: As soon as the user has entered the necessary value, the error message is removed
  • If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated – obviously the user had the intention to enter something, but failed to enter the correct value

That behaviour can be irritating when clicking through demos of the validation plugin – it is designed for an unobtrusive user experience, annoying the user as little as possible with unnecessary error messages. So when you try out other demos, try to react like one of your users would, and see if the behaviour is better then. If not, please let me know about any ideas you may have for improvements!

API Documentation

You're probably looking for

Options for the validate() method

If not, read on.

Throughout the documentation, two terms are used very often, so it's important that you know their meaning in the context of the validation plugin:

  • method: A validation method implements the logic to validate an element, like an email method that checks for the right format of a text input's value. A set of standard methods is available, and it is easy to write your own.
  • rule: A validation rule associates an element with a validation method, like "validate input with name "primary-mail" with methods "required" and "email".

Plugin methods

This library adds three jQuery plugin methods, the main entry point being the validate method:

Custom selectors

This library also extends jQuery with three custom selectors:

Validator

The validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage.

There are a few static methods on the validator object:

List of built-in Validation methods

A set of standard validation methods is provided:

Some more methods are provided as add-ons, and are currently included in additional-methods.js in the download package. Not all of them are documented here:

General Guidelines

The General Guidelines section provides detailed discussion of the design and ideas behind the plugin, explaining why certain things are as they are. It covers the features in more detail than the API documentation, which just briefly explains the various methods and options available.

If you've decided to use the validation plugin in your application and want to get to know it better, it is recommended that you read the guidelines.

Fields with complex names (brackets, dots)

When you have a name attribute like user[name], make sure to put the name in quotes. More details in the General Guidelines.

Too much recursion

Another common problem occurs with this code:

1
2
3
4
5
6
7
8
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});

This results in a too-much-recursion error: $(form).submit() triggers another round of validation, resulting in another call to submitHandler, and voila, recursion. Replace that with form.submit(), which triggers the native submit event instead and not the validation.

So the correct code looks slightly different:

1
2
3
4
5
$("#myform").validate({
submitHandler: function(form) {
form.submit();
}
});

Demos

The Marketo sign-up form

The Marketo sign-up form, step 2

Based on an old version of the marketo.com sign-up form. The custom validation was once replaced with this plugin. Thanks to Glen Lipka for contributing it!

Notable features of the demo:

  • Customized message display: No messages displayed for the required method, only for typing-errors (like wrong email format); A summary is displayed at the top ("You missed 12 fields. They have been highlighted below.")
  • Remote validation of email field. Try to enter eg. glen@marketo.com
  • Integration with masked-input plugin, see Zip and Phone fields and Credit Card Number on step 2
  • A custom method for making the billing address on step 2 optional when "Same as Company Address" is checked
  • A custom method for checking the password: Checks that the password contains at least one number and one character and that it is at least 6 characters long. If the user blurs the field with an invalid value, the input is emptied and gets focus again.

The Remember The Milk sign-up form

The sign-up form from rememberthemilk.com (based on an older version). The custom validation was replaced using this plugin. Thanks to RTM for contributing!

Notable features of the demo:

  • Custom message display, based on the original table layout, using success option to display a checkmark for valid fields
  • Remote validation of username, to check if it is already taken (try "Peter", "asdf" or "George")

A multipart "buy&sell a house" form

Contributed by Michael Evangelista, showing a multipart form for buying and selling houses.

Notable features of the demo:

  • Multipart, implemented using the jQuery UI accordion and a custom method to check if an element is on the current page when validated
  • Integration with masked-input plugin, see Phone and Zip fields

Using remote validation to help with captchas

Features remote validation for helping the user to fill out captchas, based on example atpsyrens.com.

Notable features of the demo:

  • Remote validation to check if the user entered the correct captcha, without forcing him to submit the form first


출처 - http://jqueryvalidation.org/documentation/

'Language > jQuery' 카테고리의 다른 글

jQuery Notification  (0) 2014.11.17
jQuery Colorbox  (0) 2014.11.17
jQuery Simulate  (0) 2014.11.17
https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
:

jQuery Simulate

Language/jQuery 2014. 11. 17. 15:04

http://jsfiddle.net/Ignitor/Psjhf/


Triggering Mouse Events with jQuery SimulateWhen Testing in JavaScript

With jQuery, it’s very easy to trigger mouse event handlers by calling functions such as clickmousedown and trigger. They even propagate events so that event handlers registered higher up the DOM tree through delegate() and on() would get called as well. So in most of the cases I could just use them instead of triggering real browser events when writing tests. However recently, I had to write a couple components that need to listen to mouse events such as control click, shift click and mouse drag. Looking at the jQuery API, I couldn’t find any built in functions that could trigger mouse events but at the same time specify extra properties such as control or shift click.

Googling a bit on firing real browser events and thanks to the great documentation on MDN, first an event needs to becreated, then initialized and lastly dispatched. The initMouseEvent sure makes me dizzy by  looking at it. On top of that, older IE browsers has a different API for doing the same thing. This got me thinking there gotta be a better way. What I wanted to do was just something other JavaScript UI projects must have had done. Then I took a look at the tests injQuery UI project and sure enough, I found the jquery.simulate.js to simulate real browser events and it already handles the cross browser event creation. Now let’s see how it helps me create those events that I want.

jquery.simulate.js is just another jQuery plugin and its API is fairly simple. The first parameter of the plugin is the name of the event. Here you can use the names of the browser mouse events such as click, mousemove, mouseout, etc. For example, if we want to trigger a mouse click on elements with class name “target”. We can simply call this.

1
$('.target').simulate('click');

The plugin can also take a second argument to override the default event properties. These default properties include pretty much the same arguments required to call the browser native event initialization method, event.initEvent. Two of these properties are ctrlKey and shiftKey. With them, I can now easily test my event handlers for control click and shift click.

1
2
$('.target').simulate('click', { ctrlKey: true });
$('.target').simulate('click', { shiftKey: true });

To test mouse dragging, although “drag” is not a real browser event, the plugin comes with support to handle the case when the event name specified is “drag”. We just need to specify the name as drag and the change in x and y of the mouse position. Internally, the plugin will perform a series of events including mousedown, mousemove, mouseup and click to simulate mouse drag.

1
$('.target').simulate('drag', { dx: 200, dy: 100 });

Here is a sample page that shows how the plugin works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!doctype html>
<html>
    <head>
        <title></title>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="https://raw.github.com/jquery/jquery-ui/master/tests/jquery.simulate.js"></script>
        <script type="text/javascript">
            $(function() {
                $('.target').click(function(e) {
                    if (e.ctrlKey) {
                        console.log('control click');
                    } else if (e.shiftKey) {
                        console.log('shift click');
                    } else {
                        console.log('regular click');
                    }
                }).mousedown(function(e) {console.log('mousedown', e);})
                .mouseup(function(e) { console.log('mouseup', e); });
 
                $('button').click(function() {
                    if($(this).hasClass('drag')) {
                        $('.target').simulate('drag', {dx: 100, dy: 50});
                    } else if($(this).hasClass('ctrl')) {
                        $('.target').simulate('click', {ctrlKey: true});
                    } else if($(this).hasClass('shift')) {
                        $('.target').simulate('click', {shiftKey: true});
                    } else {
                        $('.target').simulate('click');
                    }
                });
            });
        </script>
    </head>
    <body>
        <div class="target" style="background-color: yellow; height: 300px; width: 500px">Test Target</div>
        <div>
            <button class="ctrl">Ctrl Click</button>
            <button class="shift">Shift Click</button>
            <button class="regular">Regular Click</button>
            <button class="drag">Drag</button>
        </div>
    </body>
</html>

There are other options that are supported in the plugin. For complete list of options, please refer to the plugin on GitHub.

Have fun coding!


출처 - http://wingkaiwan.com/2012/09/23/triggering-mouse-events-with-jquery-simulate-when-testing-in-javascript/

'Language > jQuery' 카테고리의 다른 글

jQuery Colorbox  (0) 2014.11.17
jQuery Validation Plugin  (0) 2014.11.17
https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
jquery masked plugin  (0) 2013.02.14
:

https://code.google.com/p/jqueryjs/

Language/jQuery 2014. 11. 17. 15:03

https://code.google.com/p/jqueryjs/

'Language > jQuery' 카테고리의 다른 글

jQuery Validation Plugin  (0) 2014.11.17
jQuery Simulate  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
jquery masked plugin  (0) 2013.02.14
.get  (0) 2011.01.05
:

find, filter, children

Language/jQuery 2013. 2. 19. 10:56

jQuery에서 검색 메소드 입니다.
다양한 검색 메소드들이 있지만 이 세가지 (find, filter, children) 메소드를 헷갈릴때가 있습니다.

filter : 현재 검색된 객체(집합)에서 다시 한번 검색하는 메소드
find : 현재 검색된 객체(집합)의 자손들에서 검색 하는 메소드, 자식의 레벨은 상관없습니다.
children : 현재 검색된 객체(집합)의 직속 자식만 검색하는 메소드

filter는 검색된 결과 객체 집합에서 특정 집합으로 다시 한번 검색 할때 사용합니다.
find 검색된 결과 객체 집합의 하위레벨을 다 뒤져서(자손) 검색 할때 사용 합니다.
children 검색된 결과 객체 집하의 바로 자식들만 뒤져서(자식) 검색 할때 사용합니다.



출처 - http://ddoong2.com/413

'Language > jQuery' 카테고리의 다른 글

jQuery Simulate  (0) 2014.11.17
https://code.google.com/p/jqueryjs/  (0) 2014.11.17
jquery masked plugin  (0) 2013.02.14
.get  (0) 2011.01.05
jQuery.each(object, callback function)  (0) 2010.10.25
:

jquery masked plugin

Language/jQuery 2013. 2. 14. 12:57

http://digitalbush.com/projects/masked-input-plugin/

'Language > jQuery' 카테고리의 다른 글

https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
.get  (0) 2011.01.05
jQuery.each(object, callback function)  (0) 2010.10.25
Selectors  (0) 2010.10.25
:

.get

Language/jQuery 2011. 1. 5. 13:03

jQuery "write less, do more"

 

Traversing - Filtering

.get

설명

jQuery 오브젝트에 매치되는 DOM 엘리먼트를 되찾아온다.

jQuery 확장집합을 자바스크립트 배열로 생성해서 반환한다.

.get( [ index ] )

index : 되찾아올 엘리먼트를 가르키는 0(zero)기반의 정수

ex)

var arr = $(‘li’).get()

매개변수 없이 사용하면 jQuery 확장집합의 모든 <li> Object를 새로운 자바 스크립트 배열로 반환한다.

Arr[0].innerHTML;

기존 자바스크립트와 같이 사용 가능하다.

 

var arrDiv = $(‘div’).get(0)  // var arrDiv = $(‘div’)[0] 와 같은 소스

jQuery 확장집합의 모든 <div>의 첫번째 elementObject를 리턴한다.



결과 보기

### 출처 : http://jquery.com

[출처] [jQuery] .get()|작성자 무지개

'Language > jQuery' 카테고리의 다른 글

https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
jquery masked plugin  (0) 2013.02.14
jQuery.each(object, callback function)  (0) 2010.10.25
Selectors  (0) 2010.10.25
:

jQuery.each(object, callback function)

Language/jQuery 2010. 10. 25. 21:30

PHP의 foreach()와 유사한 기능으로 배열 또는 JSON 객체를 그 수만큼 반복하면서 호출할 수 있다.

 

var array = [ "one", "two", "three", "four", "five" ];
var object = { one:1, two:2, three:3, four:4, five:5 };

$.each(array, function() {
    $('#message > ul').append('<li>'+this+'</li>');
});

$.each(object, function(i, value) {
    $('#message > ul').append('<li>'+i+': '+value+'</li>');
});

 

실행전 HTML
<div id="message">
<ul>
    <li><strong><font color=red>each</font></strong></li>
</ul>
</div>

 

실행후 HTML
<div id="message">
<ul>

    <li><strong><font color="red">each</font></strong></li>
    <li>one</li>

    <li>two</li>

    <li>three</li>

    <li>four</li>

    <li>five</li>

    <li>one: 1</li>

    <li>two: 2</li>

    <li>three: 3</li>

    <li>four: 4</li>

    <li>five: 5</li>

</ul>
</div>

 

실행전

  • each

실행후

  • each
  • one
  • two
  • three
  • four
  • five
  • one: 1
  • two: 2
  • three: 3
  • four: 4
  • five: 5

생성한 배열과 JSON 객체 외에도 셀렉터를 사용하여 선택한 다수의 element를 각각 호출할 때에도 사용하기 때문에 jQuery를 다루면서 가장 많이 사용하게 될 Utility이다. 호출 방법은 effect의 callback function에서와 마찬가지로 this를 이용한다.

 

$('div > ul > li').each(function(i) {
    if(this.text() != 'this is li') {
        this.text('this is li!!!');
    }
});

 

실행전 HTML
<div>
<ul>
<li>this is li</li>
<li>this is div</li>
<li>this is li</li>
<li>this is li</li>
</ul>
</div>

 

실행후 HTML
<div>
<ul>
<li>this is li</li>
<li>this is li!!!</li>
<li>this is li</li>
<li>this is li</li>
</ul>
</div>

 

실행전
  • this is li
  • this is div
  • this is li
  • this is li
실행후
  • this is li
  • this is li!!!
  • this is li
  • this is li

'Language > jQuery' 카테고리의 다른 글

https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
jquery masked plugin  (0) 2013.02.14
.get  (0) 2011.01.05
Selectors  (0) 2010.10.25
:

Selectors

Language/jQuery 2010. 10. 25. 21:13

Selectors

 

 

BASIC SELECTOR

 

·         All Selector (“*”)

HTML DOCUMENT내의 모든 HTML요소(HEAD, BODY, SCRIPT) 등등의 모든 요소들을 선택하기 위함

 

·         Class Selector (“.class”)

요소의 정의되어 있는 클래스(class)를 구분자로 선택하기 위함  (.)

) <div class=”jquery”></div>  ->  $(‘.jquery’);

 

·         ID Selector (“#id”)

요소의 정의되어 있는 아이디(id)를 구분자로 선택하기 위함.  (#)

) <div id=”jquery”></div>  ->  $(‘#jquery’)

 

·         Element Selector (“element”)

일정 html 요소를 선택하기 위함 (해당 테그로 찾기 때문에 그다지 유용하진 않음). – 선택 범위가 넓기 때문

) <div></div><span></span><div></div> ->  $(‘div’);  =  2개 반환

 

·         Multiple Selector (“selector1, selector2, selectorN”)

다중으로 일정 html 요소를 선택하기 위함

) <div><span></span></div><form><input type=”text” /></form,>  ->  $(‘div, span, form, input’)

 

 

 

ATTRIBUTE SELECTOR

 

·         Attribute Contains Prefix Selector [name|=value]

이 선택자는 요소에 포함 되어 있는 속성과 속성값을 비교하여 해당 요소를 선택하기 위하여 사용 된다.

속성값이 두 단어 이상일 경우에는 아이픈(-) 으로 연결하면 선택되어 질 수 있으며 스크립트에 설정된 값은 요소에 선언된 속성값에 앞부분에 나와야 한다.

) $(‘a[wow|=you]’);  ->  모든 a 테그를 검색하고 속성 이름이 wow 인것에 값에 you 가 들어 있는 해당 요소를 반환한다   ( <a href=”#” wow=”aa-you-wow”> x ), ( <a href=”#” wow=”you-wow”> o )

 

·         Attribute Contains Selector [name*=value]

이 선택자는 요소에 포함되어 있는 속성과 속성값을 비교하여 해당 요소를 선택하기 위하여 사용 된다.

선언되어진 필요로 하는 속성값의 문자를 요소에 있는 속성값의 내용 중 아무곳에 해당 문자가 어떠한 형태로 있던 일치 하는 부분이 있다면 해당 요소를 반환하게 된다.

) $(‘input[name*=’wow’]’);  ->  우선 모든 input 테그를 검색하고 속성 name 중에 ‘wow’ 라는 문자열이 포함 되어 있다면 무조건 반환 하라.

 

·         Attribute Contains Word Selector [name~=value]

이 선택자는 요소에 포함 되어 잇는 속성과 속성값을 비교하여 해당 요소를 선택하기 위하여 사용 된다.

선언되어진 필요로 하는 속성값(단어) 를 요소에 있는 속성과 비교하여 해당 단어가 있다면 해당 요소를 반환한다. 하지만 기존의 셀렉터와는 틀리게 이 선택자는 해당 단어가 하이픈(-) 이라든지, 단어 중간에 끼어 있다면 반환하지 않으며, 공백으로 구분되어 있는 경우나, 해당 단어 하나만 있을 경우에는 요소를 반환한다.

) $(‘input[name~=’wow’]’)  ->  모든 input 테그를 검색하고 속성에 ‘wow’ 라는 단어가 독립적으로 존재하면 반환한다.

 

·         Attribute Ends With Selector [name$=value]

비교 html 요소 속성값 중 해당 속성값의 가장 뒤에 필요로 하는 단어가 붙어 있다면 해당 요소를 반환한다.

) $(‘input[name$=’wow’]’);  -> 요소 속성이 <input type=”text” name=”abcdwow” /> 로 되어야 반환

 

·         Attribute Equals Selector [name=value]

기본형태로 요소 속성값과 필요로 하는 단어가 무조건 일치하여야 해당 요소를 반환한다.

) $(‘input[name=’wow’]’);  ->  <input type=”text” name=”wow” /> 로 되어야 반환

 

·         Attribute Not Equal Selector [name!=value]

요소 속성값과 필요로 하는 단어가 일치 하지 않는 요소들을 반환한다.

This selector is equivalent to :not([attr=value]);

) $(‘input[name!=’wow’]’);  ->  <input type=”text” name=”wow” /> 반환안함 <,input type=”text” name=”wowya” /> 반환안함

 

·         Attribute Starts With Selector [name^=value]

요소 속성값과 필요로 하는 단어가 일치를 해야 하는데 전체가 일치할 필요는 없고, 필요로 하는 단어가 요소에 있는 속성값에 처음에 시작 하면 해당 요소를 반환한다.

) $(‘input[name^=’wow’]’);  ->  <input type=”text” name=”wowabcd” /> 반환함, <input type=”text” name=”abcdwow” /> 반환안함

 

·         Has Attribute Selector [name]

해당 속성이 있다면 무조건 반환한다.

) $(‘div[id]’);  ->  모든 div 를 검색하고, 해당 div id 속성이 있다면 값이 있던 없던 해당 요소를 반환한다.

 

·         Multiple Attribute Selector [name=value][name2=value2]

호출 조건을 여러 가지로 설정하여 좀더 정교한 선택을 할 수 있도록 유도 한다.

) $(‘div[id][name$=’wow’]’);  ->  모든 div 를 검색하고 그중 id 속성을 가지고 있는 요소중 name 속성이 있고 그 name 속성값에 ‘wow’ 라는 값이 가장 마지막에 있다면 해당 요소 반환

<input type=”text” id=”hey” name=”whatwow” />  반환함

 

 

FORM SELECTOR

 

·         :button Selector

버튼과 타입버튼 요소를 모두 반환함

) $(‘:button’);  ->  <button></button> 혹은 <input type=”button” /> 을 모두 반환

 

·         :checkbox Selector

타입 체크박스 요소를 모두 반환한다.

) $(‘:checkbox’);  ->  <input type=”checkbox” /> 을 모두 반환

 

·         :checked Selector

요소중 checked=”checked” 되어 있는 요소를 모두 반환한다.

) $(‘:checked’);  - >  <input type=”checkbox” checked=”checked” /> 등을 반환

 

·         :disabled Selector

요소중 disabled=”disabled” 되어 있는 요소를 모두 반환한다.

) $(‘:disabled’);  ->  <input type=”text” disabled=”disabled” /> 등을 반환

 

·         :enabled Selector

요소중 enabled 되어 있는 요소를 모두 반환한다. -> 즉 해당 요소에서 disabled 가 되지 않은 것들을 반환

) $(‘input:enabled’);

 

·         :file Selector

요소중 input type=”file” 요소를 모두 반환한다

) $(‘input:file’);

 

·         :image Selector

요소중 input type=”image” 요소를 모두 반환한다.

) $(‘input:image’);

 

·         :input Selector

영역내의 모든 요소(input, textarea, select, button) 등을 모두 반환한다 ( $(‘form > *’); )

) $(‘:input’);

 

·         :password Selector

요소중 input type=”password” 요소를 모두 반환한다

) $(‘input:password’);

 

·         :radio Selector

요소중 input type=”radio” 요소를 모두 반환한다.

) $(‘input:radio’);

 

·         :reset Selector

요소중 input type=”reset” 요소를 모두 반환한다.

) $(‘input:reset’);

 

·         :selected Selector

Select 요소의 option 항목을 위한 선택자로, option 항목이 선택 되어지는 순간 해당 선택된 option 을 반환한다.

) $(‘select’).change(function(){

       $(‘select option:selected’)………..xxxxxxxx

})

 

·         :submit Selector

요소중 input type=”sutmit” 요소를 모두 반환한다

) $(‘input:submit’);

 

·         :text Selector

요소중 input type=”text” 요소를 모두 반환한다.

) $(‘input:text’);

 

 

 

 

BASIC FILTER SELECTOR

 

·         :animated Selector

에니메이션 효과가 진행된 엘리먼트 요소를 반환한다.

) $(’element’).slideToggle(‘slow’, anymethod);  =  element slideToggle 에니메이션 실행  그후

   $(‘button’).click(function(){

            $(‘div:animated’).toggleClass(‘anyclass’);

    });

 

·         :eq() Selector

특정 엘리먼트의 :eq(index) ‘index’ 번째의 영역을 반환한다. Index “0” 부터 시작한다.

) $(‘div:eq(“2”)’).css(‘color’, ‘red’);  ->  모든 div중에 2 번째 div 에 값들에 컬러를 red로 규정한다.

 

·         :even Selector

특정 엘리먼트의 짝수번째 영역을 반환한다. 순서는 0 부터 시작한다.

) $(‘tr:even’).css(‘background-color’, ‘#000000’); ->  테이블의 tr 0부터 짝수번째 영역의 배경색은 흑색.

 

·         :first Selector

요소 중 첫번째 나오는 요소를 반환한다. 이것은 :eq(0) 과 같으며,  :lt(1) 로 사용되어도 무방하다.

) $(‘tr:first’).css(‘color’,’red’);  ->  tr 테그중 첫번째 나오는 영역을 반환한다.

 

·         :gt() Selector

요소중 :gt(index), index 번째 다음의 모든 요소를 반환한다. Index ‘0’ 부터 시작한다. :nth-child(n) n 1부터 시작 하는 것과는 대조된다.

) $(‘td:gt(2)’).css(‘border’,’red’);  -> 세번째 나오는 td 부터의 모든 td border 색상이 붉은색이다

 

·         :header Selector

Html 요소중 header 테그 h1~h6 까지의 요소들을 반환한다.

) $(‘:header’)

 

·         :last Selector

요소 중 마지막에 나오는 하나의 요소를 반환한다.

) $(‘tr:last’).css(‘color’,’red’);  ->  tr 테그중 마지막에 나오는 영역 내용의 컬러는 붉은색이다.

 

·         :lt() Selector

요소중 :lt(index), index 번째 이전의 모든 요소를 반환한다. Index ‘0’ 부터 시작한다. :nth-child(n) n 1부터 시작 하는 것과는 대조된다. (:gt(index) 와는 지정 영역이 대비된다.)

) $(‘td:lt(2)’).css(‘border’,’red’);  -> 세번째 나오는 td 이전의 모든 td border 색상이 붉은색이다

 

·         :not() Selector

특정 요소 중 주어진 조건에 맞지 않는 요소들을 반환한다.  ( :not(div a), :not(div, a) )

) $(‘input:not(:checked)’)  ->  전체 input 테그중 checked 가 되지 않는 모든 input 을 반환한다.

 

·         :odd Selector

특정 엘리먼트의 홀수번째 영역을 반환한다. 순서는 0 부터 시작한다.

) $(‘tr:odd’).css(‘background-color’, ‘#000000’); ->  테이블의 tr 0부터 홀수번째 영역의 배경색은 흑색.

 

 

 

 

CONTENTS FILTER SELECTOR

 

·         :contains() Selector

주어진 문자열이 포함 되어 있는 모든 요소를 반환한다.

) $(‘div(:contain(“ouksoo”)’).cass(‘text-decoration’,’underline’); -> ‘ouksoo’ 문자열 포함 모든 div 영역의 속성을 아래밑줄 로 정의

 

·         :empty Selector

해당 요소내 child node 혹은 text 둘 중 아무것도 없는 요소를 반환한다. 즉 비어 있는 요소를 반환한다 이 선택자는 :parent  선택자와는 반대된다..

) $(‘td:empty’).text(‘wow’); -> td 요소 중 비어 있는 td 를 찾고 그 요소안에 ‘wow’라는 문자를 넣는다.

 

·         :has() Selector

해당 요소 내에 일정(주어진) 요소가 포함 되어 있는 요소를 반환한다. 즉 반환 받고자 하는 요소는 주어진 일정한 요소를 포함하고 있어야 한다.

) $(‘div:has(p)’).addClass(“text”);  ->  모든 div 요소중 p 테그를 포함하고 있는 div ‘text’ 클레스를 적용

 

·         :parent Selector

해당 요소내 child node 혹은 text 둘 중 어떤 것이라도 포함하고 있는 요소를 반환한다. 즉 비어 있지 않는 요소를 반환한다 이 선택자는 :empty  선택자와는 반대된다..

) $(‘td:parent’).text(‘wow’); -> td 요소 중 비어 있는 td 를 찾고 그 요소안에 ‘wow’라는 문자로 치환한다.

 

 

CHILD FILTER SELECTOR

 

·         :first-child Selector

해당 구역에 포함되어 있는 요소 중 가장 첫번째 요소를 반환한다.  “nth-child(1)” 와 같다고 보면 된다

) $(‘div span:first-child’) .-> div 요소중 span 이 가장 첫번째 나올 때, 그 첫번째 span 을 반환한다.

 

·         :last-child Selector

해당 구역에 포함되어 있는 요소 중 가장 마지막 요소를 반환한다. 마지막에 선언되어진 요소가 나와야 한다.

) $(‘div span:first-child’) .-> div 요소중 span 이 가장 마지막에 나올 때, 그 마지막 span 을 반환한다.

 

·         :nth-child Selector

:nth-child(index) 에서 index 번째의 요소를 반환한다. 기존의 :eq(index) 등은 시작점이 0부터 시작하여 카운팅을 하였으나 이 셀렉터의 index 1부터 시작한다는 것에 차이가 있다.

) $(‘ul li:nth-child(2)’) -> ul 요소중 두번째 나오는 li 를 반환 / :eq(2) 일경우에는 세번째 나오는 li 를 반환.

 

·         :only-child Selector

부모영역 내에 child node 가 하나 밖에 없을 경우 해당 child 노드를 반환한다. Text node 는 여기에 child node에 포함 되지 않는다.

) $(‘div button:only-child’). -> div 요소중 button 엘리먼트를 하나만 포함 하고 있을 때 그 button  엘리먼트를 반환한다.

 

 

 

HIERARCHY(계층) SELECTOR

 

·         Child Selector (“parent > child”)

부모엘리먼트에 속해 있는 자식 엘리먼트를 반환한다. (순수계층 반환, 클래스나 아이디를 이용하여 원하는 값 도출

) $(‘ul.topclass > li’) …->  클래스명이 topclass ul 에 속해 있는 li 만 반환한다. 자식중에 클래스명을 가지지 않는 ul 이 계속 포함 되어 있더라도. 조건에 부합되진 않기 때문에 그 아래 li 는 비 반환

 

·         Descendant Selector (“ancestor descendant”)

기본 계층구조로 스페이스바에 따라 구분되며, 뒤에 나올수록 앞의 엘리먼트에 부합된며, 최종조건의 엘리먼트들을 반환한다.

) $(‘form input’)  ->  폼테그 영역에 포함 되어 있는 요소 중 input 엘리먼트는 모두 반환한다.

 

·         Next Adjacent Selector (“prev + next”)

후자(next)를 반환하는데 전자의 조건이 갖추어 져야 한다.

) $(‘label + input’); - > input 요소를 반환하는데 그 input 요조 부모가 아닌 전에 요소가 label 요소여야 반환

 

·         Next Siblings Selector (“prev ~ siblings”)

전자 조전이 시작 하는 데부터 후자 조건까지의 모든 해당 요소를 반환한다.

. First) $(‘#prev ~ div)  ->  요소들중 아이디가 prev 가 나온다면 거기서부터 나오는 div 요소 모두를 반환한다.

. Second) $(‘#prev ~ div.ouksoo’)  -> 요소들중 아이디가 prev 가 나온다면 거기서부터 나오는 div 요소중 클래스가 ouksoo인 요소들을 모두 반환한다.

 

 

VISIBILITY FILTER SELECTOR

 

·         :hidden Selector

숨어 있는 요소들을 반환한다.

-       Display ‘none’ 인 경우

-       Form element type=”hidden’ 인 경우

-       넓이나 높이가 각각 ‘0’ 으로 세팅 되어 잇는 경우

-       조상 element hidden 되어 있음 으로서 자기 자신도 보이지 않게 된 경우

 

) $(‘div:hidden’)  ->  div 요소중 보이지 않는 div 요소들을 모두 반환한다. - <div></div> 여서 보이지 않는 것을 포함되지 않는다.

 

·         :visible Selector

:hidden 과는 반대로 보여지는 모든 요소들을 반환한다.

'Language > jQuery' 카테고리의 다른 글

https://code.google.com/p/jqueryjs/  (0) 2014.11.17
find, filter, children  (0) 2013.02.19
jquery masked plugin  (0) 2013.02.14
.get  (0) 2011.01.05
jQuery.each(object, callback function)  (0) 2010.10.25
: