phpquery.php的好处可以跟jquery一样去操作DOM,对象和数组,免去了学习新的API。
在使用phpquery.php之前要加载如:
include 'phpQuery/phpQuery.php';
获取元素 pq('div') 相当于jquery的 $('div')
基础知识/Basics
加载文档,根据文档的类型不同加载不同的文档
//简单案例 phpQuery::newDocumentFileXHTML('my-xhtml.html')->find('p'); phpQuery::newDocumentFileXHTML('test.html'); //获取html文档内容 phpQuery::newDocumentFilePHP('test.php'); //获取php文档内容 phpQuery::newDocument('test.xml', 'application/rss+xml'); //默认是utf8如果不需要,要自己手动修改 phpQuery::newDocument('<div/>'); //创建新元素
phpQuery::newDocument($html, $contentType = null) Creates new document from markup. If no $contentType, autodetection is made (based on markup). If it fails, text/html in utf-8 is used.
phpQuery::newDocumentFile($file, $contentType = null) Creates new document from file. Works like newDocument()
phpQuery::newDocumentHTML($html, $charset = ‘utf-8’)
phpQuery::newDocumentXHTML($html, $charset = ‘utf-8’)
phpQuery::newDocumentXML($html, $charset = ‘utf-8’)
phpQuery::newDocumentPHP($html, $contentType = null) Read more about it on PHPSupport page
phpQuery::newDocumentFileHTML($file, $charset = ‘utf-8’)
phpQuery::newDocumentFileXHTML($file, $charset = ‘utf-8’)
phpQuery::newDocumentFileXML($file, $charset = ‘utf-8’)
phpQuery::newDocumentFilePHP($file, $contentType) Read more about it on PHPSupport page
选择器/Selectors
//选择器的使用方法跟jquery差不多,只是使用链式写法不是用点去连接而是用-> pq(".class ul > li[rel='foo']:first:has(a)")->appendTo('.append-target-wrapper div')->...
-
Basics
- #id Matches a single element with the given id attribute.
- element Matches all elements with the given name.
- .class Matches all elements with the given class.
- * Matches all elements.
- selector1, selector2, selectorN Matches the combined results of all the specified selectors.
Hierarchy
- ancestor descendant Matches all descendant elements specified by “descendant” of elements specified by “ancestor”.
- parent > child Matches all child elements specified by “child” of elements specified by “parent”.
- prev + next Matches all next elements specified by “next” that are next to elements specified by “prev”.
- prev ~ siblings Matches all sibling elements after the “prev” element that match the filtering “siblings” selector.
Basic Filters
- :first Matches the first selected element.
- :last Matches the last selected element.
- :not(selector) Filters out all elements matching the given selector.
- :even Matches even elements, zero-indexed.
- :odd Matches odd elements, zero-indexed.
- :eq(index) Matches a single element by its index.
- :gt(index) Matches all elements with an index above the given one.
- :lt(index) Matches all elements with an index below the given one.
- :header Matches all elements that are headers, like h1, h2, h3 and so on.
- :animated Matches all elements that are currently being animated.
Content Filters
- :contains(text) Matches elements which contain the given text.
- :empty Matches all elements that have no children (including text nodes).
- :has(selector) Matches elements which contain at least one element that matches the specified selector.
- :parent Matches all elements that are parents – they have child elements, including text.
Visibility Filters
none
Attribute Filters
- [attribute] Matches elements that have the specified attribute.
- [attribute=value] Matches elements that have the specified attribute with a certain value.
- [attribute!=value] Matches elements that don’t have the specified attribute with a certain value.
- [attribute^=value] Matches elements that have the specified attribute and it starts with a certain value.
- [attribute$=value] Matches elements that have the specified attribute and it ends with a certain value.
- [attribute*=value] Matches elements that have the specified attribute and it contains a certain value.
- [selector1selector2selectorN] Matches elements that have the specified attribute and it contains a certain value.
Child Filters
- :nth-child(index/even/odd/equation) Matches all elements that are the nth-child of their parent or that are the parent’s even or odd children.
- :first-child Matches all elements that are the first child of their parent.
- :last-child Matches all elements that are the last child of their parent.
- :only-child Matches all elements that are the only child of their parent.
Forms
- :input Matches all input, textarea, select and button elements.
- :text Matches all input elements of type text.
- :password Matches all input elements of type password.
- :radio Matches all input elements of type radio.
- :checkbox Matches all input elements of type checkbox.
- :submit Matches all input elements of type submit.
- :image Matches all input elements of type image.
- :reset Matches all input elements of type reset.
- :button Matches all button elements and input elements of type button.
- :file Matches all input elements of type file.
- :hidden Matches all elements that are hidden, or input elements of type “hidden”.
Form Filters
- :enabled Matches all elements that are enabled.
- :disabled Matches all elements that are disabled.
- :checked Matches all elements that are checked.
- :selected Matches all elements that are selected.
元素属性/Attributes
pq('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...
-
Attr
- attr($name) Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned.
- attr($properties) Set a key/value object as properties to all matched elements.
- attr($key, $value) Set a single property to a value, on all matched elements.
- attr($key, $fn) Set a single property to a computed value, on all matched elements.
- removeAttr($name) Remove an attribute from each of the matched elements.
Class
- addClass($class) Adds the specified class(es) to each of the set of matched elements.
- hasClass($class) Returns true if the specified class is present on at least one of the set of matched elements.
- removeClass($class) Removes all or the specified class(es) from the set of matched elements.
- toggleClass($class) Adds the specified class if it is not present, removes the specified class if it is present.
HTML
- html() Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
- html($val) Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
Text
- text() Get the combined text contents of all matched elements.
- text($val) Set the text contents of all matched elements.
Value
- val() Get the content of the value attribute of the first matched element.
- val($val) Set the value attribute of every matched element.
- val($val) Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
过滤器/查找后代元素Traversing
pq('div > p')->add('div > ul')->filter(':has(a)')->find('p:first')->nextAll()->andSelf()->...
-
Filtering
- eq($index) Reduce the set of matched elements to a single element.
- hasClass($class) Checks the current selection against a class and returns true, if at least one element of the selection has the given class.
- filter($expr) Removes all elements from the set of matched elements that do not match the specified expression(s).
- filter($fn) Removes all elements from the set of matched elements that does not match the specified function.
- is($expr) Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
- map($callback) Translate a set of elements in the jQuery object into another set of values in an array (which may, or may not, be elements).
- not($expr) Removes elements matching the specified expression from the set of matched elements.
- slice($start, $end) Selects a subset of the matched elements.
Finding
- add($expr) Adds more elements, matched by the given expression, to the set of matched elements.
- children($expr) Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
- contents() Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
- find($expr) Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
- next($expr) Get a set of elements containing the unique next siblings of each of the given set of elements.
- nextAll($expr) Find all sibling elements after the current element.
- parent($expr) Get a set of elements containing the unique parents of the matched set of elements.
- parents($expr) Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). The matched elements can be filtered with an optional expression.
- prev($expr) Get a set of elements containing the unique previous siblings of each of the matched set of elements.
- prevAll($expr) Find all sibling elements before the current element.
- siblings($expr) Get a set of elements containing all of the unique siblings of each of the matched set of elements. Can be filtered with an optional expressions.
Chaining
- andSelf() Add the previous selection to the current selection.
- end() Revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state (right before the destructive operation).
元素的增、删、改/Manipulation
-
Changing Contents
- html() Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
- html($val) Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
- text() Get the combined text contents of all matched elements.
- text($val) Set the text contents of all matched elements.
Inserting Inside
- append($content) Append content to the inside of every matched element.
- appendTo($content) Append all of the matched elements to another, specified, set of elements.
- prepend($content) Prepend content to the inside of every matched element.
- prependTo($content) Prepend all of the matched elements to another, specified, set of elements.
Inserting Outside
- after($content) Insert content after each of the matched elements.
- before($content) Insert content before each of the matched elements.
- insertAfter($content) Insert all of the matched elements after another, specified, set of elements.
- insertBefore($content) Insert all of the matched elements before another, specified, set of elements.
Inserting Around
- wrap($html) Wrap each matched element with the specified HTML content.
- wrap($elem) Wrap each matched element with the specified element.
- wrapAll($html) Wrap all the elements in the matched set into a single wrapper element.
- wrapAll($elem) Wrap all the elements in the matched set into a single wrapper element.
- wrapInner($html) Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.
- wrapInner($elem) Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
Replacing
- replaceWith($content) Replaces all matched elements with the specified HTML or DOM elements.
- replaceAll($selector) Replaces the elements matched by the specified selector with the matched elements.
Removing
- empty() Remove all child nodes from the set of matched elements.
- remove($expr) Removes all matched elements from the DOM.
Copying
- clone() Clone matched DOM Elements and select the clones.
- clone($true) Clone matched DOM Elements, and all their event handlers, and select the clones.
php版本的Ajax
Ajax Requests
- phpQuery::ajax($options) Load a remote page using an HTTP request.
- load($url, $data, $callback) Load HTML from a remote file and inject it into the DOM.
- phpQuery::get($url, $data, $callback) Load a remote page using an HTTP GET request.
- phpQuery::getJSON($url, $data, $callback) Load JSON data using an HTTP GET request.
- phpQuery::getScript($url, $callback) Loads, and executes, a local JavaScript file using an HTTP GET request.
- phpQuery::post($url, $data, $callback, $type) Load a remote page using an HTTP POST request.
Ajax Events
- ajaxComplete($callback) Attach a function to be executed whenever an AJAX request completes. This is an Ajax Event.
- ajaxError($callback) Attach a function to be executed whenever an AJAX request fails. This is an Ajax Event.
- ajaxSend($callback) Attach a function to be executed before an AJAX request is sent. This is an Ajax Event.
- ajaxStart($callback) Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event.
- ajaxStop($callback) Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.
- ajaxSuccess($callback) Attach a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.
Misc
- phpQuery::ajaxSetup($options) Setup global settings for AJAX requests.
- serialize() Serializes a set of input elements into a string of data. This will serialize all given elements.
- serializeArray() Serializes all forms and form elements (like the .serialize() method) but returns a JSON data structure for you to work with.
事件/Events
pq('form')->bind('submit', 'submitHandler')->trigger('submit')->... function submitHandler($e) { print 'Target: '.$e->target->tagName; print 'Bubbling ? '.$e->currentTarget->tagName; }
Event Handling
- bind($type, $data, $fn) Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
- one($type, $data, $fn) Binds a handler to one or more events to be executed once for each matched element.
- trigger($type , $data ) Trigger a type of event on every matched element.
- triggerHandler($type , $data ) This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
- unbind($type , $data ) This does the opposite of bind, it removes bound events from each of the matched elements.
Interaction Helpers
none
Event Helpers
- change() Triggers the change event of each matched element.
- change($fn) Binds a function to the change event of each matched element.
- submit() Trigger the submit event of each matched element.
- submit($fn) Bind a function to the submit event of each matched element.
对象、数组、函数工具/Utilities
Array and Object operations
- phpQuery::each($object, $callback) A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
- phpQuery::grep($array, $callback, $invert) Filter items out of an array, by using a filter function.
- phpQuery::makeArray($obj) Turns an array-like object into a true array.
- phpQuery::map($array, $callback) Translate all items in an array to another array of items.
- phpQuery::inArray($value, $array) Determine the index of the first parameter in the Array (-1 if not found).
- phpQuery::unique($array) Remove all duplicate elements from an array of elements.
Test operations
- phpQuery::isFunction($obj) Determine if the parameter passed is a function.
String operations
- phpQuery::trim($str) Remove the whitespace from the beginning and end of a string.
JSON
$jsonString = phpQuery::toJSON( pq('form')->serializeArray() ); $array = phpQuery::parseJSON('{"foo": "bar"}');