Home >Web Front-end >JS Tutorial >js skills collection (more than 200) highly recommended_basic knowledge

js skills collection (more than 200) highly recommended_basic knowledge

PHP中文网
PHP中文网Original
2016-05-16 19:19:431422browse

1. Text box focus problem
onBlur: This event is generated when the input focus is lost
onFocus: This file is generated when the input gains focus
Onchange: When the text value changes, this event is generated
Onselect: When the text is highlighted, this event is generated

The text disappears when clicked and reappears when the focus is lost


2. Special colors for web buttons

style="background-color:rgb(235,207,22)">

3. The color changes when the mouse moves in and out

onMouseOver=this.style.color="red" class="button">

4. Flat button


5. Button color changes


6. Plane input box


7. Make the window the specified size
<script> <br>window.resizeTo(300,283); <br></script>

8. Make the text scroll up and down

height=60>



Republic
                                                                   


9. The status bar displays the status of the page


10. You can click on the text to select the radio option






11. You can write onclick events in the font of the text field

12. PrintPrint web page


13. Line input box

class="line">

14. Display the last modification date of the document


15. The event can be triggered when the mouse moves over the text





link



16. The page color can be determined according to the options on the web page


background.html

<SCRIPT> <br><!-- <br/><br/>function bgChange(selObj) { <br/> newColor = selObj.options[selObj.selectedIndex].text; <br/> document.bgColor = newColor; <br/> selObj.selectedIndex = -1; <br/> } <br/><br/>//--> <br></SCRIPT>

Changing Background Colors


 


  
 




17.将按钮的特征改变
 
  本例按钮的代码如下:

onmouseout="this.className='style1'" class="style1"> 

18.改变按钮的图片.
 
  本例的按钮代码如下: 

onmouseout="this.className='style3'" class="style3">

19.打印页面
打印本稿


20. You can write html language directly
document.write("");

21. Change the color of the drop-down box

>guoqiang99859

25.layer2 is the ID of the component, which can control whether the component is visible
document.all.item('Layer2').style.display = "block";
document.all.item('Layer2').style.display = "none";//

26. Add the page to favorites
//

27. Automatically close the page after 10 seconds
< script language="JavaScript" >
function closeit() {
setTimeout("self.close()", 10000)
}
< /script >

28. You can compare the size of characters
char=post.charAt(i);
if(!('0'<=char&&char<='9'))

29. Convert characters to numbers
month = parseInt(char)

30. When clicking on an option with a non-empty value, redirect to the specified connection


31. Change the background color

onmouseout="this.bgColor='#FAFBFC';">

32. Change the background color of the text input box



33. Change the characteristics of the horizontal line



34. How to pass parameters
8

35. In-page jump
1
2
3
4
5
6
7
dfdf
dfdf//

36. Press both buttons together
if(event.ctrlKey && window.event.keyCode==13)//

37. Refresh the page
javascript:this.location.reload()//

38. Enable the button on the web page






39.文字移动


40.双击网页自动跑
//

41.后退


42.前进


43.刷新


44.转向指定网页
document.location="http://ww"或者document.location.assign("http://guoguo.com")

45.在网页上显示实时时间
//

46.可以下载文件 
document.location.href="目标文件"//

47.连接数据库
import java.sql.*;
String myDBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(myDBDriver);
Connection conn=DriverManager.getConnection("jdbc:odbc:firm","username","password");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
rs.getString("column1");//

48.可以直接在页面“div”内写下所需内容

//

49. You can change the format of the connection on the page to make it a double line


Complete css


50. New frame

href="javascript:newframe('http://www.163.net/help/a_little/index.html','http://www.163.net/help/a_little

/a_13.html')">help< ;/a>

51. Write content to the file
<%@ page import="java.io.*" %>
<%
String str = "print me";
//always give the path from root. This way it almost always works.
String nameOfTextFile = "/usr/anil/imp.txt";
try
{
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(str);
//clean up
pw.close();
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>

52. Read the file first and then write the file
<%@ page language = "java" %>
<%@ page contentType = "text/html; charSet=gb2312" %>
<%@ page import ="java.util.*" %>
<%@ page import ="java.lang.*" %>
<%@ page import ="javax.servlet.*" %>
<%@ page import ="javax.servlet.jsp.*" %>
<%@ page import ="javax.servlet.http.*" %>
<%@ page import="java.io.*" %>
eryrytry
<%
int count=0;
FileInputStream fi =new FileInputStream ("count.txt");
ObjectInputStream si= new ObjectInputStream (fi);
count =si.readInt();
count ;
out.print(count);
si.close();

FileOutputStream fo =new FileOutputStream ("count.txt");
ObjectOutputStream so= new ObjectOutputStream (fo);
so.writeInt(count);
so.close();
%>

53. Linear input box


54.可以将背景改为按钮性状,通过改变css改变属性

onmouseout=this.className='mouseout';>

color="#000000">录音笔



55.同时按下CTRL和Q键
document.onkeydown=function()
{
if(event.ctrlKey&&event.keyCode==81)
{alert(1)}
}//

56.以下是一个完整的显示hint的代码,其思想是当鼠标停留是将div中的内容显示在鼠标出,当鼠标移出后在将该div隐

藏掉
---------------------------------------------------------------------------------------------------------

------------






dfdfd



-------------------------------------------------- -------------------------------------------------- --------

---------------------

57. Pop-up window
Method 1: A window pops up when the browser reads the page;
Method 2: A window pops up when the browser leaves the page;
Method 3: Call with a connection: Open a window
Note: The "#" used is a virtual connection.​
Method 4: Use a button to call: When to load script


58. Dynamically change the font size
function doZoom(size)
{
document.getElementById('zoom').style.fontSize=size 'px'
}

function aa()
{
var newWin=window.open(url);
newWin.document.form1.text1.value=value1;
}Change the properties of the field on the pop-up window
opener.document.form2.text2.value=value2;Change the value of the domain of the parent window

59. Determine what kind of browser it is
var name = navigator.appName;
if (name == "Microsoft Internet Explorer")
alert("IE");
else if (name == "Netscape")
alert("NS");//

60.vbsscript OK box
//

61. Copy content to clipboard
function JM_cc(bb)
{
var ob=eval("document.form1." bb);
ob.select();
js=ob.createTextRange();
js.execCommand("Copy");
}// Establish a database connection in 62.java to retrieve data
public void init()
{
String url="jdbc:odbc:javadata";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection(url,"sa","");//mssql database user SA and password
DatabaseMetaData dma=con.getMetaData();
System.out.println("Connect to" dma.getURL());
System.out.println(";Driver " dma.getDriverName());
System.out.println(";Version " dma.getDriverVersion());
System.out.println("");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from company.dbo.TB_NAME where number=1");//Sql
rs.next();
String dispresult=rs.getString("name");
System.out.println(dispresult);// Instead, you can display it in Paint() or use AWT etc.
rs.close();
stmt.close();
con.close();
}
catch(SQLException ex)
{
System.out.println("!!!SQL Exception !!!");
while(ex!=null)
{
System.out.println("SQLState:" ex.getSQLState());
System.out.println("Message:" ex.getMessage());
System.out.println("Vendor:" ex.getErrorCode());
ex=ex.getNextException();
System.out.println("");
}

}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
}//


63. Minimize window
window.blur()//


64. Document path
document.URL//

65. Execute a certain program regularly
setTimeout("change_color()",600);

66. Set as homepage
function makeHome(){
netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
navigator.preference("browser.startup.homepage", location.href);
}//

67. Set as favorites
function addFav(){
if(ie)
window.external.AddFavorite(location.href,'WWW.OGRISH.COM : GROTESQUE MOVIES AND PICTURES');
if(ns)
alert("Thanks for the bookmark!nnNetscape users click OK then press CTRL-D");
}//

68. Determine whether cookies are available
navigator.cookieEnabled;//

69. Display a modal pop-up window with pages
function setbgcolor_onclick()
{
var color = showModalDialog("/mailpage/compose/colorsel.html",0,"help=0");
if (color != null)
{
document.compose.bgcolor.value = color;
}
}//


70.Truncate to two decimal places
var a=3454545.4454545;
alert(a.toFixed(2));//


71. It is forbidden to select text on the page to copy
<script> <br>function noEffect() { <br> with (event) { <br> returnValue = false; <br> cancelBubble = true; <br> } <br> return; <br>} <br></script>
//

72. Block the right-click menu
oncontextmenu="event.returnValue = false"//

73. Event bubbles are prohibited
event.cancelBubble = true//

74. Input method is prohibited from opening in the input box
//

75. Block Chinese characters and spaces
//

76. Use javascript to determine whether a file exists
function Exists(filespec)
{
if (filespec)
{
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
alert(fso.FileExists(filespec));
}
}
Select image


//

77. Get the text selected in the current text box
//

78. Jump to the target page and cannot return.
sohu.com//


79. Get which row of the table the current row is.
<script> <br>function getrow(obj) <br>{ <br> if(event.srcElement.tagName=="TD"){ <br> curRow=event.srcElement.parentElement; <br> alert("This is the "(curRow.rowIndex 1) "row"); <br><br> } <br>} <br></script>
















     
       
//

80. Delete a certain row of the table, xx represents a certain row, and the subscript starts from 0
document.all.myTable.deleteRow(xx)//

81. Dynamically add rows to the table





4 people
backdepth='15pt' on='true'/>



4 people
backdepth='15pt' on='true'/>
//



101. Pie chart






onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com'

CoordSize='10,10' strokecolor='white' fillcolor='#ffff33'>


onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com'

CoordSize='10,10' strokecolor='white' fillcolor='#ff9933'>


onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com' 

CoordSize='10,10' strokecolor='white' fillcolor='#3399ff'>
300,200,200,150,11010048,3145728 xe'/>

onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com' 

CoordSize='10,10' strokecolor='white' fillcolor='#99ff33'>
300,200,200,150,14155776,4718592 xe'/>

onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com' 

CoordSize='10,10' strokecolor='white' fillcolor='#ff6600'>
300,200,200,150,18874368,3145728 xe'/>

onmouseover='javascript:show(this);' onmouseout='javascript:hide(this);' href='http://www.cnADO.com' 

CoordSize='10,10' strokecolor='white' fillcolor='#ff99ff'>
300,200,200,150,22020096,1572864 xe'/>





style='fontsize:2'>asp技术


style='fontsize:2'>php


style='fontsize:2'>jsp


style='fontsize:2'>c#写的.netWEB程序

vb.net

写的.netWEB程序

xml技术





 
style="border-collapse: collapse" bordercolor="#CCCCCC" width="100%" ID="Table1">
  
   
  
 
 

//

102. It is a special container. You can install a web page wherever you want.
//button

103. External html code
event.srcElement.outerHTML//

104. Identifies the trigger of the current IE event
event.srcElement and event.keyCode//

105. Event type
event.type//

106. Dynamically change the type

//

107. Page flip
//

108. Scroll
parent.scroll(x,y);//
//

109. Change the status bar
self.status ="";//

110. Change the window size
window.resizeTo(200,300);//

111. Change mouse style
style
BODY{CURSOR: url('mouse.ani');
SCROLLBAR-BASE-COLOR: #506AA8;
SCROLLBAR-ARROW-COLOR: #14213F;
}//

112. Transparent background
//

113. The mouse is in the waiting shape
//

114. Call the function of the parent window
opener.fucntion1();//

115.body’s internal html code
//

116. Functions that call the parent window in the frame
//

117. Exchange node



CELL_1
CELL_2



//

118. Delete node



CELL_1
CELL_2



//

119. Add node
addNode()//

120. Get the parent and child tags of the event
event.srcElement.children[0] and event.srcElement.parentElement //


121. Centrally change the color of buttons

//


122. Determine whether the left or right button is pressed
//

123. Get the name of the operating system and the name of the browser
document.write(navigator.userAgent)//


124.Alt/ctrl/shift key is pressed
event.altKey //Press the alt key
event.ctrlKey //Press the ctrl key
event.shiftKey //Press the shift key



125. Locate the current location to C drive.
{window.location="c:"}//

126. Return the type of input box
<script> <br>alert(event.srcElement.type);// <br></script>

127. Simulate the click event of the control

//


128. Get the column names of the record set
java.sql.ResultSet rset = com.bsitc.util.DBAssist.getIT().executeQuery(queryStatement, conn);
java.sql.ResultSetMetaData metaData = rset.getMetaData();
int count = metaData.getColumnCount();
String name = metaData.getColumnName(i);
String value = rset.getString(i);//

129. Format numbers
function format_number(str,digit)
{
if(isNaN(str))
{
alert("The value you passed in is not a number!");
return 0;
}
else if(Math.round(digit)!=digit)
{
alert("The number of decimal places you entered is not an integer!");
return 0;
}
else
return Math.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit);
}

130. Convert the Enter button to a tab button
if(event.keyCode==13) event.keyCode=9; //Convert


131. Scroll bar scrolling


//


132. Determine what object it is
if(typeof(unknown)=="function")return true;
if(typeof(unknown)!="object")return false;//


133. Cancel the text box auto-complete function
//

134. Let the drop-down box drop down automatically
//


135. Read XML file
var childrenobj=myselect//document.all.myselect;
var oXMLDoc = new ActiveXObject('MSXML');
oXMLDoc.url = "mymsg.xml";
var oRoot=oXMLDoc.root;
if(oRoot.children != null)
{
for(var i=0;i {
oItem = oRoot.children.item(0).children.item(i);
oOption = new Option(oItem.text,oItem.value);
childrenobj.add(oOption);




Hangzhou area

Wenzhou area



Taizhou area

Lishui area

//


136. Click on the picture, the picture will stop
//

137. Display local computer information
var WshNetwork = new ActiveXObject("WScript.Network");
alert("Domain = " WshNetwork.UserDomain);
alert("Computer Name = " WshNetwork.ComputerName);
alert("User Name = " WshNetwork.UserName);//


138. Compare time
tDate = new Date(2004,01,08,14,35); //Year, month, day, hour, minute
dDate = new Date();
tDate
139. Pop up the link address where the mouse is located

href="http://51js.com/viewthread.php?tid=13589" >dddd
//

140. Note that you cannot test whether a variable exists by comparing it to undefined, although you can check whether its type is "undefined". in In the code example below

, assume that the programmer wants to test whether the variable x has been declared:
// This method does not work
if (x == undefined)
// Do something
// This method also does not work - must check


// String "undefined"
if (typeof(x) == undefined)
// Perform certain operations
// This method is valid
if (typeof(x) == "undefined")
// Do some operations

141. Create an object with certain properties
var myObject = new Object();
myObject.name = "James";
myObject.age = "22";
myObject.phone = "555 1234";//

142. Enumerate (loop) all properties of the object
for (var a in myObject)
{
// Display "The property 'name' is James", etc.
window.alert("The property '" a "' is " myObject[a]);
}//

143. Determine whether a number is an integer
var a=23.2;
alert(a%1==1)//


144. Create a new date variable
var a = new Date(2000, 1, 1);
alert(a.toLocaleDateString());


145. Define new methods for classes
function trim_1()
{
return this.replace(/(^s*)|(s*$)/g, "");
}
String.prototype.trim=trim_1;
alert('cindy'.trim());


146. Define a method to convert date type into string
function guoguo_date()
{
var tmp1,tmp2;
tmp1 =this.getMonth() 1 "";
if(tmp1.length<2)
tmp1="0" tmp1;
tmp2 =this.getDate() "";
if(tmp2.length<2)
tmp2="0" tmp2;

return this.getYear() "-" tmp1 "-" tmp2;
}
Date.prototype.toLiteString=guoguo_date;
alert(new Date().toLiteString())



147. Pasta is a constructor with four parameters, defining an object.
function pasta(grain, width, shape, hasEgg)
{
// What kind of grain is it made of?
this.grain = grain;

// How wide? (numeric value)
this.width = width;

// Cross-sectional shape? (string)
this.shape = shape;

// Do you want to add egg yolk? (boolean)
this.hasEgg = hasEgg;

//Define method
this.toString=aa;
}
function aa()
{

}
//After defining the object constructor, use the new operator to create an object instance.
var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);
//Supplementary definition attributes, both spaghetti and linguine will automatically obtain new attributes
pasta.prototype.foodgroup = "carbohydrates";


148. Print out the error reason
try
{
x = y // An error occurs.
}
catch(e)
{
document.write(e.description) //Print "'y' is undefined".
}//

149. Generate Excel file and save it
var ExcelSheet;
ExcelApp = new ActiveXObject("Excel.Application");
ExcelSheet = new ActiveXObject("Excel.Sheet");
//This code starts the application that creates the object (in this case, a Microsoft Excel worksheet). Once the object is created, you can use the defined pair

Reference it in your code like a variable. In the following example, the properties and methods of the new object and other Excel objects are accessed through the object variable ExcelSheet,

Includes the Application object and the ActiveSheet.Cells collection.​
// Make Excel visible through the Application object.
ExcelSheet.Application.Visible = true;
//Place some text into the first cell of the table.
ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1";
// Save the form.
ExcelSheet.SaveAs("C:\TEST.XLS");
// Use the Application object to close Excel using the Quit method.
ExcelSheet.Application.Quit();//

150. Get a set of objects based on tags
var coll = document.all.tags("DIV");
if (coll!=null)
{
for (i=0; i...
}//

151. Realize print preview and printing


//

152. Reference the object directly by name without passing the form

//

153. Disable the mouse wheel
function document.onmousewheel()
{
return false;
}//

154. Create a pop-up window
//

155. Get the object where the mouse is located
var obj = document.elementFromPoint(event.x,event.y);//

156. Get the object on the left

onclick="this.previousSibling.value='guoguo'">//

157. Position the mouse
document.all.hint_layer.style.left = event.x document.body.scrollLeft 10;
document.all.hint_layer.style.top = event.y document.body.scrollTop 10;//

158. Add an item to the specified location of the drop-down box
var op = document.createElement("OPTION");
document.all.selected_items.children(index).insertAdjacentElement("BeforeBegin",op);
op.text = document.all.all_items[i].text;
op.value = document.all.all_items[i].value;//


159. Determine whether a window has been opened. If it is already open, close it
var a;
if(a)
a.close();
else
a=window.open('','','');//

160. Create a label dynamically
newElem = document.createElement("DIV");
newElem.id = "hint_layer";
document.body.appendChild(newElem);
document.all.hint_layer.innerText="guoguo";//

161. Title bar
document.title//

162.Background image
//The background image is not fixed

//The background image is centered

163. Set transparency effect
document.form.xxx.filters.alpha.opacity=0~100//

164.Definition method
var dragapproved=false;
document.onmouseup=new Function("dragapproved = false");//

165. Convert numbers into RMB capital form
function convertCurrency(currencyDigits) {
// Constants:
var MAXIMUM_NUMBER = 99999999999.99;
// Predefine the radix characters and currency symbols for output:
var CN_ZERO = "zero";
var CN_ONE = "one";
var CN_TWO = "two";
var CN_THREE = "三";
var CN_FOUR = "Four";
var CN_FIVE = "五";
var CN_SIX = "Lu";
var CN_SEVEN = "旒";
var CN_EIGHT = "捌";
var CN_NINE = "玖";
var CN_TEN = "十";
var CN_HUNDRED = "hundred";
var CN_THOUSAND = "Thousand";
var CN_TEN_THOUSAND = "Ten thousand";
var CN_HUNDRED_MILLION = "Billion";
var CN_SYMBOL = "RMB";
var CN_DOLLAR = "yuan";
var CN_TEN_CENT = "corner";
var CN_CENT = "fen";
var CN_INTEGER = "whole";

// Variables:
var integral; // Represent integral part of digit number.
var decimal; // Represent decimal part of digit number.
var outputCharacters; // The output result.
var parts;
var digits, radices, bigRadices, decimals;
var zeroCount;
var i, p, d;
var quotient, modulus;

// Validate input string:
currencyDigits = currencyDigits.toString();
if (currencyDigits == "") {
alert("Empty input!");
return "";
}
if (currencyDigits.match(/[^,.d]/) != null) {
alert("Invalid characters in the input string!");
return "";
}
if ((currencyDigits).match(/^((d{1,3}(,d{3})*(.((d{3},)*d{1,3})))?) |(d (.d )?))$/) == null) {
alert("Illegal format of digit number!");
return "";
}

// Normalize the format of input digits:
currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
currencyDigits = currencyDigits.replace(/^0 /, ""); // Trim zeros at the beginning.
// Assert the number is not greater than the maximum number.
if (Number(currencyDigits) > MAXIMUM_NUMBER) {
alert("Too large a number to convert!");
return "";
}

// http://www.knowsky.com/ Process the conversion from currency digits to characters:
// Separate integral and decimal parts before processing copying:
parts = currencyDigits.split(".");
if (parts.length > 1) {
integral = parts[0];
decimal = parts[1];
// Cut down redundant decimal digits that are after the second.
decimal = decimal.substr(0, 2);
}
else {
integral = parts[0];
decimal = "";
}
// Prepare the characters corresponding to the digits:
digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT,

CN_NINE);
radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
decimals = new Array(CN_TEN_CENT, CN_CENT);
// Start processing:
outputCharacters = "";
 // Process integral part if it is larger than 0:
 if (Number(integral) > 0) {
  zeroCount = 0;
  for (i = 0; i < integral.length; i++) {
p = integral.length - i - 1;
d = integral.substr(i, 1);
quotient = p / 4;
modulus = p % 4;
if (d == "0") {
zeroCount++;
}
else {
if (zeroCount > 0)
    {
     outputCharacters += digits[0];
    }
    zeroCount = 0;
    outputCharacters += digits[Number(d)] + radices[modulus];
   }
   if (modulus == 0 && zeroCount < 4) {
    outputCharacters += bigRadices[quotient];
   }
  }
  outputCharacters += CN_DOLLAR;
 }
 // Process decimal part if there is:
 if (decimal != "") {
  for (i = 0; i < decimal.length; i++) {
   d = decimal.substr(i, 1);
   if (d != "0") {
    outputCharacters += digits[Number(d)] + decimals[i];
   }
  }
 }
 // Confirm and return the final output string:
 if (outputCharacters == "") {
  outputCharacters = CN_ZERO + CN_DOLLAR;
 }
 if (decimal == "") {
  outputCharacters += CN_INTEGER;
 }
 outputCharacters = CN_SYMBOL + outputCharacters;
 return outputCharacters;
}//

 
166.xml数据岛绑定表格



















接收人 发送人 主题 内容
表格的结束




//cd_catalog.xml
 
  
 
 
  Empire Burlesque 
  Bob Dylan 
  USA 
  Columbia 
  10.90 
  1985 
  

 
  Hide your heart 
  Bonnie Tyler 
  UK 
  CBS Records 
  9.90 
  1988 
  

 
  Greatest Hits 
  Dolly Parton 
  USA 
  RCA 
  9.90 
  1982 
  

 
  Still got the blues 
  Gary Moore 
  UK 
  Virgin records 
  10.20 
  1990 
  


//


167.以下组合可以正确显示汉字
================================
xml保存编码 xml页面指定编码
ANSI  gbk/GBK、gb2312
Unicode  unicode/Unicode
UTF-8  UTF-8
================================

 
168.XML操作


<script> <br>var x=xmldata.recordset //Get the record set in the data island <br>if(x.absoluteposition < x.recordcount) //If the current absolute position is before the last record <br>{ <br> x.movenext(); //Move backwards <br> x.moveprevious(); //Move forward <br> x.absoluteposition=1; //Move to the first record <br> x.absoluteposition=x.recordcount;//Move to the last record, note that the record set x.absoluteposition is from 1 to the number of records in the record set <br><br>Number of <br> guoguo.innerText=xmldso.recordset("field_name"); //Get a record from it <br>} <br></script>


169. Another way to dynamically modify CSS
this.runtimeStyle.cssText = "color:#990000;border:1px solid #cccccc";//

170. Regular expression
Regular expression matching Chinese characters: [u4e00-u9fa5]

Matches double-byte characters (including Chinese characters): [^x00-xff]

Application: Calculate the length of a string (a double-byte character is counted as 2, and ASCII characters are counted as 1)

String.prototype.len=function(){return this.replace([^x00-xff]/g,"aa").length;}

Regular expression matching empty lines: n[s| ]*r

Regular expression matching HTML tags: /<(.*)>.*|<(.*) />/

Regular expression matching leading and trailing spaces: (^s*)|(s*$)

Application: There is no trim function like vbscript in JavaScript. We can use this expression to achieve it, as follows:

String.prototype.trim = function()
{
return this.replace(/(^s*)|(s*$)/g, "");
}

///////Use regular expressions to decompose and convert IP addresses:

The following is a Javascript program that uses regular expressions to match IP addresses and convert IP addresses into corresponding values:

function IP2V(ip)
{
re=/(d ).(d ).(d ).(d )/g //Regular expression matching IP address
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3)) RegExp.$2*Math.pow(255,2)) RegExp.$3*255 RegExp.$4*1
}
else
{
throw new Error("Not a valid IP address!")
}
}

However, if the above program does not use regular expressions, it may be simpler to use the split function to decompose it directly. The program is as follows:

var ip="10.100.20.168"
ip=ip.split(".")
alert("The IP value is: " (ip[0]*255*255*255 ip[1]*255*255 ip[2]*255 ip[3]*1))

Regular expression matching email addresses: w ([- .]w )*@w ([-.]w )*.w ([-.]w )*

Regular expression matching URL: http://([w-] .) [w-] (/[w- ./?%&=]*)?

//////////Algorithm program that uses regular expressions to remove repeated characters in a string:

var s="abacabefgeeii"
var s1=s.replace(/(.).*1/g,"$1")
var re=new RegExp("[" s1 "]","g")
var s2=s.replace(re,"")
alert(s1 s2) //The result is: abcefgi

The idea is to use back references to extract the repeated characters, then use the repeated characters to create a second expression, obtain non-repeated characters, and concatenate the two. This way The

method may not be applicable to strings that require character order.

//////////A javascript program that uses regular expressions to extract file names from URL addresses. The following result is page1

s="http://www.9499.net/page1.htm"
s=s.replace(/(.*/){0,}([^.] ).*/ig,"$2")
alert(s)

////////Use regular expressions to limit the input content of the text box in the web form:

Use regular expressions to limit input to Chinese only: onkeyup="value=value.replace(/[^u4E00-u9FA5]/g,'')"

onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^u4E00-u9FA5]/g,'')

)"

Use regular expressions to limit the input of only full-width characters: onkeyup="value=value.replace(/[^uFF00-uFFFF]/g,'')"

onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,'')

)"

Use regular expressions to limit the input of numbers only: onkeyup="value=value.replace(/[^d]/g,'')

"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"

Use regular expressions to limit input to numbers and English only: onkeyup="value=value.replace(/[W]/g,'')

"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"

 
171.设置和使用cookie


设置与读取 cookies...

写入cookie的值






function Set()
{
var Then = new Date() 
Then.setTime(Then.getTime()   60*1000 ) //60秒
document.cookie = "Cookie1=" gg.value ";expires="  Then.toGMTString() 
}

function Get()

 var cookieString = new String(document.cookie)
 var cookieHeader = "Cookie1="
 var beginPosition = cookieString.indexOf(cookieHeader)
 if (beginPosition != -1)
 {
  document.all.Textbox.value = cookieString.substring(beginPosition    cookieHeader.length) 
 }
 else
  document.all.Textbox.value = "Cookie 未找到!" 
}
 
//

 
172.取月的最后一天
function getLastDay(year,month)
{
 //取年
 var new_year = year;
 //取到下一个月的第一天,注意这里传入的month是从1~12 
 var new_month = month ;
 //如果当前是12月,则转至下一年
 if(month>12)
 {
  new_month -=12;
  new_year ;
 }
 var new_date = new Date(new_year,new_month,1);
 return (new Date(new_date.getTime()-1000*60*60*24)).getDate();
}//

173.判断当前的焦点是组中的哪一个
for(var i=0;i<3;i )
 if(event.srcElement==bb[i])
  break;//

 

174.实现类
package com.baosight.view.utils;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.http.HttpSession;
public class Mytag extends TagSupport 
{
  public int doStartTag() throws javax.servlet.jsp.JspException 
  {
    boolean canAccess = false;
    HttpSession session= pageContext.getSession();
    if (canAccess) 
    {
      return EVAL_BODY_INCLUDE;
    }
    else 
    {
      return this.SKIP_BODY;
    }
  }
}

175.在web.xml中添加定义
  
    guoguo
    /WEB-INF/abc.tld
  



176.标签库中定义abc.tld

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

 1.0
 1.1
 hr
 guoguo
 Extra 3 Tag Library
 
  mytag
  com.baosight.view.utils.Mytag
  
id2
true
                                                                                                                    





177. Add your own defined tags to pages that use custom tags.
<%@ taglib uri="guoguo" prefix="guoguo" %>
//Define your own tag


178. Display set with border

Query conditions
dfdfdf
//


179. Implementation of the commands in the [File (F)] menu

1. Implementation of the 〖Open〗 command
[Format]:document.execCommand("open")
[Explanation] This is somewhat similar to the commands in the webbrowser control in VB and other programming designs. You can also think about it based on this.
[Example] Add between :
Open

2. Implementation of the 〖Use Notepad Edit〗 command
[Format]:location.replace("view-source:" location)
[Instructions] Open Notepad and display the source code of the web page in Notepad.
[Example] Add between :
Use Notepad to edit

3. Implementation of the "Save As" command
[Format]: document.execCommand("saveAs")
[Instructions] Save this web page to another directory on the local disk!
[Example] Add between :
Save as

4. Implementation of the [Print] command
[Format]: document.execCommand("print")
[Explanation] Of course, you must have a printer installed!
[Example] Add between :
Print

5. Implementation of the 〖Close〗 command
[Format]:window.close();return false
[Explanation] This window will be closed.
[Example] Add between :
Close this window

180. Implementation of the command in the [Edit (E)] menu

Implementation of the "Select All" command
[Format]:document.execCommand("selectAll")
[Description] All content in the web page will be selected!
[Example] Add between :
Select All

181. Implementation of the command in the [View (V)] menu

1. Implementation of the 〖Refresh〗 command
[Format]:location.reload() or history.go(0)
[Instructions] Reopen this page with the browser.
[Example] Add between :
Refresh
Or add:
Refresh

2. Implementation of the 〖Source File〗 command
[Format]:location.replace("view-source:" location)
[Description] View the source code of this webpage.
[Example] Add between :
View source file

3. Implementation of the "Full Screen Display" command
[Format]:window.open(document.location, "url", "fullscreen")
[Description] Display this page in full screen.
[Example] Add between :
Full screen display

182. Implementation of the command in the [Favorites (A)] menu

1. Implementation of the "Add to Favorites" command
[Format]:window.external.AddFavorite('url', '"Website name")
[Description] Add this page to favorites.
[Example] Add between :
Add to Inbox

Favorites


2. Implementation of the 〖Organize Favorites〗 command
[Format]:window.external.showBrowserUI("OrganizeFavorites",null)
[Instructions] Open the organize favorites dialog box.
[Example] Add between :
Organize favorites

183. Implementation of the command in the [Tools (T)] menu

Implementation of the 〖internet option〗 command
[Format]:window.external.showBrowserUI("PrivacySettings",null)
[Description] Open the internet options dialog box.
[Example] Add between :
internet options

184. Implementation of commands in [Toolbar]

1. Implementation of [Forward] command
[Format] history.go(1) or history.forward()
[Explanation] The browser opens the next page.
[Example] Add between :
Forward
Or join:
Forward

2. Implementation of the "Back" command
[Format]: history.go(-1) or history.back()
[Description] The browser returns to the previous viewed page.
[Example] Add between :
Back
Or join:
Back

3. Implementation of 〖Refresh〗
[Format]:document.reload() or history.go(0)
[Instructions] Reopen this page with the browser.
[Example] Add between :
Refresh
Or add:
Refresh

185. Implementation of other commands
Implementation of the 〖Close this window regularly〗 command
[Format]: settimeout(window.close(), closing time)
[Description] This window will be closed.
[Example] Add between :
Close this window in 3 seconds


[Attachment] For the convenience of readers, all example codes are listed below. You can put them into an html file and preview the effect.
Open

Use Notepad to edit

Save as

Print

Close this window

Select All

Refresh Refresh< ;/a>

View source file

Full screen display

Add to favorites

Clip


Organize favorites

internet options

Forward 1 Forward 2< ;/a>

Back 1 Back 2

Close this window in 3 seconds



186. Add a new attribute to the tag in DHTML, you can add it at will


//


187.xmlhttp technology
This method is to obtain the XML document from the server through the XMLHTTP object. The example is as follows.​


//

188. The server side obtains the incoming string through request.getReader()

189. Using regular expressions in java
java.util.regex.Pattern p =

java.util.regex.Pattern.compile("\d |.\d |\d .\d*|(E|\d E|.\d E|\d .\d*E )((\ |-)\d|\d)\d*");
java.util.regex.Matcher m = p.matcher("12.E 3");
boolean result = m.matches();//


190. Group drop-down boxes
//

191. Add phonetic notation

Basic text
Phonetic text
//


192. Strikethrough
This text will appear strikethrough. //

193. Get the event event in the frame
document.frames("workspace").event.keyCode//

194. is the definition of the pop-up method
String.prototype.trim=function()
{
return this.replace(/(^s*)|(s*$)/g, "");
}
alert(" ".trim)//


195. Prevent web pages from being included
if (window != window.top)
top.location.href = location.href;//


196. Keep the web page in the frame
if(window==window.top)
{
document.body.innerHTML="

Please access this page through normal methods!

";
//window.close();
}//


197. Add as homepage
<SCRIPT> <br>function fnSet(){ <br>oHomePage.setHomePage(location.href); <br>event.returnValue = false; <br>} <br></SCRIPT>
//


198.xml data island operation

The record set in the data island in HTML


Editing and adding XML data island records in HTML




Hotel name:

Address:

Home page:

Email:

Telephone:

Level:










Sihai Hotel
No. 1 Haihun Road

www.sihaohotel.com.cn
master@sihaohotel.com.cn
(0989)8888888
Five-star


Wuhu Hotel
No. 99, Dongping Road

www.wuhu.com.cn
web@wuhu.com.cn
(0979)1111666
Four-star


"Great Desert" Hotel
No. 168, Liuxiang Road

www.dashamohotel.com.cn
master@dashamohotel.com.cn
(0989)87878788
Five-star


Thrush Hotel
No. 2, Xuehai Piaoxiang Road

www.throstlehotel.com.cn
chuliuxiang@throstlehotel.com.cn
(099)9886666
Five-star





   //xml数据岛中添加记录


-------------------------------
  The following list is a sample of the properties and methods that you use to access nodes in an XML 

document.

Property/    Method Description 
XMLDocument Returns a reference to the XML Document Object Model (DOM) exposed by the object.  

documentElement  Returns the document root of the XML document. 
childNodes    Returns a node list containing the children of a node (if any). 
item     Accesses individual nodes within the list through an index. Index values are zero-based, so 

item(0) returns the first child node. 
text     Returns the text content of the node. 

The following code shows an HTML page containing an XML data island. The data island is contained within 

the  element.


  
    HTML with XML Data Island
  
  
    

Within this document is an XML data island.



    
      
        Adventure Works
        Alpine Ski House
      

    


  

For an example, you can cut and paste this sample line of code: 

resortXML.XMLDocument.documentElement.childNodes.item(1).text//读取页面上的XML数据岛中的数据
resortXML.documentElement.childNodes.item(0).getAttribute("code")//读取页面上的XML数据岛中的数据
resortXML.documentElement.childNodes[0].getAttribute("code")//读取页面上的XML数据岛中的数据

199.模式窗口
父窗口
var url="aaa.jsp";
var 

data=showModalDialog(url,null,"dialogHeight:400px;dialogHeight:600px;center:yes;help:No;status:no;resizab

le:Yes;edge:sunken");
if(data)
 alert(data.value);

子窗口
var data=new Object();
data.value1="china";
window.returnValue=data;
window.close();

 
200.动态设置事件,带参数



//

 
201.将url转化为16进制形式
 var ret = '';

 for(var i=0; i < str.length; i )
 {
  var ch = str.charAt(i);
  var code = str.charCodeAt(i);

  if(code < 128 && ch != '[' && ch != ''' && ch != '=')
  {
   ret  = ch;
  }
  else 
  {
   ret  = "["   code.toString(16)   "]";
  }
 }
 return ret;//


202.打开新的窗口并将新打开的窗口设置为活动窗口
var newWin=window.open("xxxx");
newWin.focus();//


203. Fault Tolerance Script
No action is taken when a script error is encountered in JS: window.onerror = doNothing;
The syntax for specifying an error handle is: window.onerror = handleError
function handleError(message, URI, line)
{// Prompts the user that this page may not respond correctly
return true; // This will terminate the default message
}//Operation when the page error occurs

Window redirection in 204.JS:
window.navigate("http://www.sina.com.cn");//

205. Prevent link text from wrapping
document.body.noWrap=true;//

206. Determine whether the characters match.
string.match(regExpression)//

207.
href="javascript:document.Form.Name.value='test';void(0);"//Cannot use onClick="javascript:document.Form.Name.v

alue='test';return false;"

When using the inline method to add event handling scripts, there is a process of being packaged into an anonymous function, that is to say
onClick="javacript:document.Form.Name.value='test';return false;" is packaged as:
functoin anonymous()
{
Document.Form.Name.value='test';return false;
}
As a member function of A onclick.
And href="javascript:document.Form.Name.value='test';void(0);" is equivalent to executing a global statement. If you use the return statement, it will

Report errors when using return statements outside functions.


208. Enlarge the page


sdsdsdsdsdsdsdsds

//

209. Place it on the far right of the page
//

210. Use style to control the display of different colors on alternate lines







//

211. Maximize full screen
newwindow=window.open("","","scrollbars")
if (document.all)
{
newwindow.moveTo(0,0)
newwindow.resizeTo(screen.width,screen.height)
}//

212. Parse node values ​​in xml based on name
var XMLDoc=new ActiveXObject("MSXML");
XMLDoc.url="d:/abc.xml";
aRoot=XMLDoc.root;
a1.innerText=aRoot.children.item("name").text;//


213. Parse xml value on the page
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/5996c682-3472-4b03-9fb0-1e08

fcccdf35.asp
//

214. See how many carriage returns there are in a string, the return value is an array
var s=value.match(/n/g);if(s)if(s.length==9){alert('10 lines');return false;}//

215. Get asc code
var s='aa';
alert(s.charCodeAt(1))//

216. Text aligned to the right
//

217. Determine whether a method exists
function pageCallback(response){
alert(response);
}
if(pageCallback)
alert(1)//


218. Determine whether a variable is defined
if(typeof(a)=="undefined")
{
alert()
}//


219.javascript executes the local executable program and needs to be set to trusted or reduce the IE security level
<script> <br>function exec (command) { <br> window.oldOnError = window.onerror; <br> window._command = command; <br> window.onerror = function (err) { <br> if (err.indexOf('utomation') != -1) { <br> alert('The command has been banned by the user!'); <br>        return true; <br>      } <br>      else return false; <br>    }; <br>    var wsh = new ActiveXObject('WScript.Shell'); <br>    if (wsh) <br>      wsh.Run(command); <br>    window.onerror = window.oldOnError; <br>  } <br></script>
调用方式
测试//

220.弹出新页面,关闭旧页面,不弹出提示框
 var w=screen.availWidth-10;
   var h=screen.availHeight-10;
   var swin=window.open("/mc/mc/message_management.jsp", 

"BGSMbest","scrollbars=yes,status,location=0,menubar=0,toolbar=0,resizable=no,top=0,left=0,height="+h+",w

idth="+w);
   window.opener=null;
   window.close();//

221.能输入的下拉框



 //

 
222.在方法中定义全局变量
function globalVar (script) {
        eval(script);//all navigators
  //window.execScript(script); //for ie only 
}
globalVar('window.haha = "../system";');
alert(haha);//在方法中定义全局变量,其中的haha就是全局变量了

223.显示一个对象的全部的属性和属性的值
var a=new Object();
a.name='a1';
a.***='mail'
for(var p in a)
{
 alert(p+"="+a[p])
}//

 
224.16进制转换成10进制
var n = parseInt("2AE",16);//这里将16进制的 2AE 转成 10 进制数,得到 n 的值是 686


225.复制粘贴



//

226.
스위치(object.constructor){
케이스 날짜:
...
사례 번호:
...
사례 문자열:
...
케이스 MyObject:
...
기본값:
...
}//


227. 이미지 로딩 실패 시 이미지 다시 로드
//

228
//font_효과.htc




//abc.css
tr{behavior:url(font_ effect.htc);}

229. CSS와 HTC를 통해 테이블 ​​색상을 변경할 수 있습니다. IE에서만 지원됩니다.
//xxx.html










1 2 3
4 5 6
//

230. 페이지에 점을 그립니다.
함수 a(x,y,color)
{
document.write("")
}//

231. 웹페이지 자동 닫기

이 페이지는 10초 후에 자동으로 닫힙니다.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn