classroom.dtd文件:<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT classroom (claName,grade,students)>
<!ATTLIST classroom id ID #REQUIRED>
<!ELEMENT claName (#PCDATA)>
<!ELEMENT grade (#PCDATA)>
<!ELEMENT students (student+)>
<!ELEMENT student (id,stuName,age)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT stuName (#PCDATA)>
<!ELEMENT age (#PCDATA)>
classroom.xml文件:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE classroom SYSTEM "classroom.dtd">
<classroom id="c1">
<claName>10计算机应用技术</claName>
<grade>2010</grade>
<students>
<student>
<id>1</id>
<stuName>zhangsan</stuName>
<age>12</age>
</student>
<student>
<id>2</id>
<stuName>lisi</stuName>
<age>122</age>
</student>
</students>
</classroom>
private static String ns = "
http://service.soap.org/";
private static String wsdlUrl = "
http://localhost:8989/ms?wsdl";public static void test02() {
try {
//1���创建服务(Service)
URL url = new URL(wsdlUrl);
QName sname = new QName(ns,"MyServiceImplService");
Service service = Service.create(url,sname);
//2����创建Dispatch
Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
SOAPMessage.class, Service.Mode.MESSAGE);
//3����创建SOAPMessage
SOAPMessage msg = MessageFactory.newInstance().createMessage();
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
SOAPBody body = envelope.getBody();
//4���创建QName来指定消息中传递数据����
QName ename = new QName(ns,"add","nn");//<nn:add xmlns="xx"/>
SOAPBodyElement ele = body.addBodyElement(ename);
ele.addChildElement("a").setValue("22");
ele.addChildElement("b").setValue("33");
msg.writeTo(System.out);
System.out.println("\n invoking.....");
//5�通过Dispatch传递消息,会返回响应消息
SOAPMessage response = dispatch.invoke(msg);
response.writeTo(System.out);
System.out.println("\n----------------------------------------");
//��将响应的消息转换为dom对象��
Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
System.out.println(str);
} catch (SOAPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void test06() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//通过DocumentBuilder创建doc的文档对象
Document doc = db.parse(is);
//创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
//第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for(int i=0;i<list.getLength();i++) {
//遍历输出相应的结果
Element e = (Element)list.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public static void test07() {
try {
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xsw.writeStartDocument("UTF-8","1.0");
xsw.writeEndDocument();
String ns = "
http://11:dd";
xsw.writeStartElement("nsadfsadf","person",ns);
xsw.writeStartElement(ns,"id");
xsw.writeCharacters("1");
xsw.writeEndElement();
xsw.writeEndElement();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}
@Test
public static void test08() {
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//通过DocumentBuilder创建doc的文档对象
Document doc = db.parse(is);
//创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
Transformer tran = TransformerFactory.newInstance().newTransformer();
tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
tran.setOutputProperty(OutputKeys.INDENT, "yes");
//第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
//获取price节点
Element be = (Element)list.item(0);
Element e = (Element)(be.getElementsByTagName("price").item(0));
e.setTextContent("333.9");
Result result = new StreamResult(System.out);
//通过tranformer修改节点
tran.transform(new DOMSource(doc), result);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void test05() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//基于Filter的过滤方式,可以有效的过滤掉不用进行操作的节点,效率会高一些
XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),
new EventFilter() {
@Override
public boolean accept(XMLEvent event) {
//返回true表示会显示,返回false表示不显示
if(event.isStartElement()) {
String name = event.asStartElement().getName().toString();
if(name.equals("title")||name.equals("price"))
return true;
}
return false;
}
});
int num = 0;
while(reader.hasNext()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
num++;
}
System.out.println(num);
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void test04() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//基于迭代模型的操作方式
XMLEventReader reader = factory.createXMLEventReader(is);
int num = 0;
while(reader.hasNext()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
num++;
}
System.out.println(num);
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void test01() {
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = null;
try {
is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext()) {
// System.out.println("------------------------------------------------");
int type = reader.next();
System.out.println("type---"+type);
//判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
if(type==XMLStreamConstants.START_ELEMENT) {//==1,指示事件是一个开始元素
System.out.println(reader.getName());
String name = reader.getName().toString();
if("book".equals(name)){
System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
}else if("title".equals(name)){
System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
}
// System.out.println("==1,指示事件是一个开始元素");
} else if(type==XMLStreamConstants.CHARACTERS) {//==4指示事件是一些字符
System.out.println(reader.getText().trim());
// System.out.println("==4指示事件是一些字符");
} else if(type==XMLStreamConstants.END_ELEMENT) {//==2,指示事件是一个结束元素
System.out.println("/"+reader.getName());
// System.out.println("==2,指示事件是一个结束元素");
}
//else if(type==XMLStreamConstants.ATTRIBUTE){
// int count = reader.getAttributeCount();
// System.out.println("count========"+count);
// if(count>0){
// int i=0;
// int[] arr = new int[count];
// while(i<count){
// arr[i]=i;
// i++;
// }
// for(int a : arr){
// System.out.println(reader.getAttributeValue(a));
// }
// }
// }
}
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
try {
if(is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
学生类
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Student {
private int id;
private String name;
private int age;
private Classroom classroom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Classroom getClassroom() {
return classroom;
}
public void setClassroom(Classroom classroom) {
this.classroom = classroom;
}
public Student(int id, String name, int age, Classroom classroom) {
super();
this.id = id;
this.name = name;
this.age = age;
this.classroom = classroom;
}
public Student() {
super();
}
}
教室类
public class Classroom {
private int id;
private String name;
private int grade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Classroom(int id, String name, int grade) {
super();
this.id = id;
this.name = name;
this.grade = grade;
}
public Classroom() {
super();
// TODO Auto-generated constructor stub
}
}
测试类:
public class TestJaxb {
public static void main(String[] args){
TestJaxb.test02();
}
@Test
public static void test01() {//测试对象转换xml字符串
try {
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Marshaller marshaller = ctx.createMarshaller();
Student stu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010));
marshaller.marshal(stu, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
@Test
public static void test02() {//测试xml字符串转换对象
try {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>21</age><classroom><grade>2010</grade><id>1</id><name>10计算机应用技术</name></classroom><id>1</id><name>张三</name></student>";
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Unmarshaller um = ctx.createUnmarshaller();
Student stu = (Student)um.unmarshal(new StringReader(xml));
System.out.println(stu.getName()+","+stu.getClassroom().getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
1简历webservice服务的步骤:
(1)服务器的建立:1:创建接口SEI(Service Endpoint Interface)
@WebService()
public interface IMyService
{
@WebResult(name="addResult")
public int add(@WebParam(name="a")int
a,@WebParam(name="b")int b);
@WebResult(name="minusResult")
public int minus(@WebParam(name="a")int
a,@WebParam(name="b")int b);
@WebResult(name="loginUser")
public User login(@WebParam(name="username")String
username,@WebParam(name="password")String password);
}
2:创建实现类SIB(Service inplemention Bean)
@WebService(endpointInterface="org.zttc.service.IMyService")
public class MyServiceImpl
implements IMyService {
@Override
public int add(int a, int b) {
System.out.println(a+"+"+b+"="+(a+b));
return a+b;
}
@Override
public int minus(int a, int b) {
System.out.println(a+"-"+b+"="+(a-b));
return a-b;
}
@Override
public User login(String username, String password) {
System.out.println(username+" is logining");
User user = new User();
user.setId(1);
user.setUsername(username);
user.setPassword(password);
return user;
}
}
3:开启服务
public class MyServer {
public
static void main(String[] args) {
String
address = "http://localhost:8888/ns";
Endpoint.publish(address,
new MyServiceImpl());
}
}
在浏览器地址栏中输入; http://localhost:8888/ns?wsdl,看到页面上出现xml文件。
(2)客户端的建立:
public class TestClient {
public
static void main(String[] args) {
try
{
创建访问wsdl服务地址的url
URL
url = new URL("http://localhost:8888/ns?wsdl");
通过qname指明服务的具体信息
QName
sname = new QName("http://service.zttc.org/",
"MyServiceImplService");
创建服务
Service
service = Service.create(url,sname);
实现接口
IMyService
ms = service.getPort(IMyService.class);
System.out.println(ms.add(12,33));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
3.wsdl的有关参数:
types:用来定义访问的类型
message:SOAP
portType:指明服务器的接口,并且通过operation绑定相应的in和out的消息:其中in表示参数,out表示返回值
binding:指定传递消息所使用的格式
service:指定服务所发布的名称
4:dtd的例子:
classroom.dtd
<?xml version="1.0"
encoding="UTF-8"?>
<!ELEMENT classroom
(claName,grade,students)>
<!ATTLIST classroom id ID #REQUIRED>
<!ELEMENT claName (#PCDATA)>
<!ELEMENT grade (#PCDATA)>
<!ELEMENT students (student+)>
<!ELEMENT student (id,stuName,age)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT stuName (#PCDATA)>
<!ELEMENT age (#PCDATA)>
classroom.xml
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE classroom SYSTEM
"classroom.dtd">
<classroom id="c1">
<claName>10计算机应用技术</claName>
<grade>2010</grade>
<students>
<student>
<id>1</id>
<stuName>zhangsan</stuName>
<age>12</age>
</student>
<student>
<id>2</id>
<stuName>lisi</stuName>
<age>122</age>
</student>
</students>
</classroom>
1.得到访问的文件地址
<script type="text/javascript">
with(location){
var qs = search.substring(1);
var hostName = hostname; //unavailable when viewing from a local file
var url = href;
}
alert(qs);
alert(hostName);
alert(url);
</script>
<script type="text/javascript">
// == 表示两个对象的toString相等
//===表示两个对象的类型相等且值相等。
alert(null == undefined); //true
alert(null === undefined); //false
alert("NaN" == NaN); //false
alert("NaN" === NaN); //false
alert(NaN == NaN); //false
alert(NaN === NaN); //false
alert(NaN != NaN); //true
alert(NaN !== NaN); //true
alert(false == 0); //true
alert(false === 0); //false
alert(true == 1); //true
alert(true === 1); //false
alert(null == 0); //false
alert(undefined == 0); //false
alert(5 == "5"); //true
alert(5 === "5"); //false
</script>
<script type="text/javascript">
alert(null == undefined); //true
alert(null === undefined); //false
alert("NaN" == NaN); //false
alert("NaN" === NaN); //false
alert(NaN == NaN); //false
alert(NaN === NaN); //false
alert(NaN != NaN); //true
alert(NaN !== NaN); //true
alert(false == 0); //true
alert(false === 0); //false
alert(true == 1); //true
alert(true === 1); //false
alert(null == 0); //false
alert(undefined == 0); //false
alert(5 == "5"); //true
alert(5 === "5"); //false
</script>
<script type="text/javascript">
var result1 = ("55" != 55); //false ?equal because of conversion
var result2 = ("55" !== 55); //true ?not equal because different data types
alert(result1);
alert(result2);
var result1 = ("55" == 55); //true ?equal because of conversion
var result2 = ("55" === 55); //false ?not equal because different data types
</script>
得到window中所有的事件
<script type="text/javascript">
for (var propName in window) {
document.write(propName);
document.write("<br />");
}
</script>
<script type="text/javascript">
for (var propName in window) {
document.write(propName);
document.write("<br />");
}
</script>
方法参数数组
<script type="text/javascript">
function sayHi() {
alert("Hello " + arguments[0] + ", " + arguments[1]);
}
sayHi("Nicholas", "how are you today?");
function howManyArgs() {
alert(arguments.length);
}
howManyArgs("string", 45); //2
howManyArgs(); //0
howManyArgs(12); //1 </script>
<script type="text/javascript">
function sayHi() {
alert("Hello " + arguments[0] + ", " + arguments[1]);
}
sayHi("Nicholas", "how are you today?");
</script>
null的类型
<script type="text/javascript">
var car = null;
alert(typeof car); //"object"
alert(null == undefined); //true </script>
<script type="text/javascript">
var car = null;
alert(typeof car); //"object"
</script>
1 Javascript数组转换为CSV格式
首先考虑如下的应用场景,有一个Javscript的字符型(或者数值型)数组,现在需要转换为以逗号分割的CSV格式文件。则我们可以使用如下的小技巧,代码如下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.valueOf();
输出:apple,peaches,oranges,mangoes
其中,valueOf()方法会将Javascript数组转变为逗号隔开的字符串。要注意的是,如果想不使用逗号分割,比如用|号分割,则请使用join方法,如下:
- var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
- var str = fruits.join("|");
输出: apple|peaches|oranges|mangoes
2 将CSV格式重新转换回Javscript数组
那么如何将一个CSV格式的字符串转变回Javascript数组呢?可以使用split()方法,就可以使用任何指定的字符去分隔,代码如下:
- var str = "apple, peaches, oranges, mangoes";
- var fruitsArray = str.split(",");
输出 fruitsArray[0]: apple
3 根据索引移除数组中的某个元素
假如需要从Javascript数组中移除某个元素,可以使用splice方法,该方法将根据传入参数n,移除数组中移除第n个元素(Javascript数组中从第0位开始计算)。
- function removeByIndex(arr, index) {
- arr.splice(index, 1);
- }
- test = new Array();
- test[0] = 'Apple';
- test[1] = 'Ball';
- test[2] = 'Cat';
- test[3] = 'Dog';
- alert("Array before removing elements: "+test);
- removeByIndex(test, 2);
- alert("Array after removing elements: "+test);
则最后输出的为Apple,Ball,Dog
4 根据元素的值移除数组元素中的值
下面这个技巧是很实用的,是根据给定的值去删除数组中的元素,代码如下:
- function removeByValue(arr, val) {
- for(var i=0; i<arr.length; i++) {
- if(arr[i] == val) {
- arr.splice(i, 1);
- break;
- }
- }
- }
-
- var somearray = ["mon", "tue", "wed", "thur"]
-
- removeByValue(somearray, "tue");
-
-
当然,更好的方式是使用prototype的方法去实现,如下代码:
- Array.prototype.removeByValue = function(val) {
- for(var i=0; i<this.length; i++) {
- if(this[i] == val) {
- this.splice(i, 1);
- break;
- }
- }
- }
-
- var somearray = ["mon", "tue", "wed", "thur"]
- somearray.removeByValue("tue");
5 通过字符串指定的方式动态调用某个方法
有的时候,需要在运行时,动态调用某个已经存在的方法,并为其传入参数。这个如何实现呢?下面的代码可以:
- var strFun = "someFunction";
- var strParam = "this is the parameter";
- var fn = window[strFun];
-
-
- fn(strParam);
6 产生1到N的随机数
- var random = Math.floor(Math.random() * N + 1);
-
-
- var random = Math.floor(Math.random() * 10 + 1);
-
-
- var random = Math.floor(Math.random() * 100 + 1);
7 捕捉浏览器关闭的事件
我们经常希望在用户关闭浏览器的时候,提示用户要保存尚未保存的东西,则下面的这个Javascript技巧是十分有用的,代码如下:
- <script language="javascript">
- function fnUnloadHandler() {
-
- alert("Unload event.. Do something to invalidate users session..");
- }
- </script>
- <body onbeforeunload="fnUnloadHandler()">
- ………
- </body>
就是编写onbeforeunload()事件的代码即可
8 检查是否按了回退键
同样,可以检查用户是否按了回退键,代码如下:
- window.onbeforeunload = function() {
- return "You work will be lost.";
- };
9 检查表单数据是否改变
有的时候,需要检查用户是否修改了一个表单中的内容,则可以使用下面的技巧,其中如果修改了表单的内容则返回true,没修改表单的内容则返回false。代码如下:
- function formIsDirty(form) {
- for (var i = 0; i < form.elements.length; i++) {
- var element = form.elements[i];
- var type = element.type;
- if (type == "checkbox" || type == "radio") {
- if (element.checked != element.defaultChecked) {
- return true;
- }
- }
- else if (type == "hidden" || type == "password" ||
- type == "text" || type == "textarea") {
- if (element.value != element.defaultValue) {
- return true;
- }
- }
- else if (type == "select-one" || type == "select-multiple") {
- for (var j = 0; j < element.options.length; j++) {
- if (element.options[j].selected !=
- element.options[j].defaultSelected) {
- return true;
- }
- }
- }
- }
- return false;
- }
- window.onbeforeunload = function(e) {
- e = e || window.event;
- if (formIsDirty(document.forms["someForm"])) {
-
- if (e) {
- e.returnValue = "You have unsaved changes.";
- }
-
- return "You have unsaved changes.";
- }
- };
10 完全禁止使用后退键
下面的技巧放在页面中,则可以防止用户点后退键,这在一些情况下是需要的。代码如下:
- <SCRIPT type="text/javascript">
- window.history.forward();
- function noBack() { window.history.forward(); }
- </SCRIPT>
- </HEAD>
- <BODY onload="noBack();"
- onpageshow="if (event.persisted) noBack();" onunload="">
11 删除用户多选框中选择的项目
下面提供的技巧,是当用户在下拉框多选项目的时候,当点删除的时候,可以一次删除它们,代码如下:
- function selectBoxRemove(sourceID) {
-
- var src = document.getElementById(sourceID);
-
- for(var count= src.options.length-1; count >= 0; count--) {
-
- if(src.options[count].selected == true) {
- try {
- src.remove(count, null);
-
- } catch(error) {
-
- src.remove(count);
- }
- }
- }
- }
12 Listbox中的全选和非全选
如果对于指定的listbox,下面的方法可以根据用户的需要,传入true或false,分别代表是全选listbox中的所有项目还是非全选所有项目,代码如下:
- function listboxSelectDeselect(listID, isSelect) {
- var listbox = document.getElementById(listID);
- for(var count=0; count < listbox.options.length; count++) {
- listbox.options[count].selected = isSelect;
- }
- }
13 在Listbox中项目的上下移动
下面的代码,给出了在一个listbox中如何上下移动项目
- unction listbox_move(listID, direction) {
-
- var listbox = document.getElementById(listID);
- var selIndex = listbox.selectedIndex;
-
- if(-1 == selIndex) {
- alert("Please select an option to move.");
- return;
- }
-
- var increment = -1;
- if(direction == 'up')
- increment = -1;
- else
- increment = 1;
-
- if((selIndex + increment) < 0 ||
- (selIndex + increment) > (listbox.options.length-1)) {
- return;
- }
-
- var selValue = listbox.options[selIndex].value;
- var selText = listbox.options[selIndex].text;
- listbox.options[selIndex].value = listbox.options[selIndex + increment].value
- listbox.options[selIndex].text = listbox.options[selIndex + increment].text
-
- listbox.options[selIndex + increment].value = selValue;
- listbox.options[selIndex + increment].text = selText;
-
- listbox.selectedIndex = selIndex + increment;
- }
-
-
-
- listbox_move('countryList', 'up');
- listbox_move('countryList', 'down');
14 在两个不同的Listbox中移动项目
如果在两个不同的Listbox中,经常需要在左边的一个Listbox中移动项目到另外一个Listbox中去,下面是相关代码:
- function listbox_moveacross(sourceID, destID) {
- var src = document.getElementById(sourceID);
- var dest = document.getElementById(destID);
-
- for(var count=0; count < src.options.length; count++) {
-
- if(src.options[count].selected == true) {
- var option = src.options[count];
-
- var newOption = document.createElement("option");
- newOption.value = option.value;
- newOption.text = option.text;
- newOption.selected = true;
- try {
- dest.add(newOption, null);
- src.remove(count, null);
- }catch(error) {
- dest.add(newOption);
- src.remove(count);
- }
- count--;
- }
- }
- }
-
-
-
- listbox_moveacross('countryList', 'selectedCountryList');
15 快速初始化Javscript数组
下面的方法,给出了一种快速初始化Javscript数组的方法,代码如下:
- var numbers = [];
- for(var i=1; numbers.push(i++)<100;);
-
- 使用的是数组的push方法
16 截取指定位数的小数
如果要截取小数后的指定位数,可以使用toFixed方法,比如:
- var num = 2.443242342;
- alert(num.toFixed(2));
- 而使用toPrecision(x)则提供指定位数的精度,这里的x是全部的位数,如:
- num = 500.2349;
- result = num.toPrecision(4);
17 检查字符串中是否包含其他字符串
下面的代码中,可以实现检查某个字符串中是否包含其他字符串。代码如下:
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function(obj, start) {
- for (var i = (start || 0), j = this.length; i < j; i++) {
- if (this[i] === obj) { return i; }
- }
- return -1;
- }
- }
-
- if (!String.prototype.contains) {
- String.prototype.contains = function (arg) {
- return !!~this.indexOf(arg);
- };
- }
在上面的代码中重写了indexOf方法并定义了contains方法,使用的方法如下:
- var hay = "a quick brown fox jumps over lazy dog";
- var needle = "jumps";
- alert(hay.contains(needle));
18 去掉Javscript数组中的重复元素
下面的代码可以去掉Javascript数组中的重复元素,如下:
- function removeDuplicates(arr) {
- var temp = {};
- for (var i = 0; i < arr.length; i++)
- temp[arr[i]] = true;
-
- var r = [];
- for (var k in temp)
- r.push(k);
- return r;
- }
-
-
- var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
- var uniquefruits = removeDuplicates(fruits);
-
19 去掉String中的多余空格
下面的代码会为String增加一个trim()方法,代码如下:
- if (!String.prototype.trim) {
- String.prototype.trim=function() {
- return this.replace(/^\s+|\s+$/g, '');
- };
- }
-
-
- var str = " some string ";
- str.trim();
-
20 Javascript中的重定向
在Javascript中,可以实现重定向,方法如下:
- window.location.href = "http://viralpatel.net";
21 对URL进行编码
有的时候,需要对URL中的传递的进行编码,方法如下:
- var myOtherUrl =
- "http://example.com/index.html?url=" + encodeURIComponent(myUrl);