Friday, October 26, 2007

Javascript 中变量的声明和变量的作用域说明

一、全局作用域和局部作用域
在全局环境里:
var a = 1;

a = 1;
的作用是相同的。但是如果是在一个函数体内这二者就不同了,前者是声明了一个函数体内的局部变量,而后者在此函数被运行一次之后就会生成一个全局变量 a 。
一般在声明变量时尽可能的加上var。
二、delete与变量关系:
按JavaScript权威指南书中所言,一个变量一旦被 var 声明之后(未初始化)就有一个默认值'undefined',并delete运算符不能删除这些变量,不然会引发一个错误。不过在Firefox中测试是可以对声明后的变量进行delete,并返回true,在操作之后再引用就会报未定义错误,说明变量正常删除。在IE7里进行delete是的确返回false,无法删除,不过也没有引发错误。
三、JavaScript没有块级作用域
这个不同于C/C++/Java,Javascript的变量只要声明了就会在整个函数体中都有定义,而不管声明的前后位置,会覆盖全局的同名变量。


function test(o) {
var i = 0; // i is defined throughout function
if (typeof o == "object") {
var j = 0; // j is defined everywhere, not just block
for(var k=0; k < 10; k++) { // k is defined everywhere, not just loop
document.write(k);
}
document.write(k); // k is still defined: prints 10
}
document.write(j); // j is defined, but may not be initialized
}

var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
alert(scope); // Displays "local"
}
f( );

在桌面上显示回收站图标

REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Folder\RecycleBinOnDesktop]
"RegPath"="Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel"
"Text"="在桌面上显示回收站图标"
"Type"="checkbox"
"valueName"="{645FF040-5081-101B-9F08-00AA002F954E}"
"Checkedvalue"=dword:00000000
"Uncheckedvalue"=dword:00000001
"Defaultvalue"=dword:00000001
"HKeyRoot"=dword:80000001

然后打开“资源管理器-工具-选项-查看”,先将“在桌面上显示回收站图标”这项选上“应用”再去掉勾“应用”即可控制桌面显示与不显示垃圾桶回收站。

Wednesday, October 24, 2007

替代cookie在客户端实现数据持久性

在这个页面进行数据存储(仅限IE userData持久性)


<html>
<body>
<!-- This stylesheet defines a class named "persistent" -->
<style>.persistent { behavior:url(#default#userData);}</style>
<!-- This <div> element is a member of that class -->
<div id="memory" class="persistent"></div>

<script type="text/javascript">
var memory = document.getElementById("memory"); // Get persistent element
memory.setAttribute("username", 'user_name'); // Set data as attributes
memory.setAttribute("favoriteColor", '#ddd');

var now = (new Date( )).getTime( ); // now, in milliseconds
var expires = now + 10 * 24 * 60 * 60 * 1000; // 10 days from now in ms
memory.expires = (new Date(expires)).toUTCString( ); // convert to a string

memory.save("myPersistentData"); // Save the data

</script>
</body>
</html>

可以在这个页面读取,类似于操作cookie:

<html>
<body>
<!-- This stylesheet defines a class named "persistent" -->
<style>.persistent { behavior:url(#default#userData);}</style>
<!-- This <div> element is a member of that class -->
<div id="memory" class="persistent"></div>

<script type="text/javascript">
document.write("test result: <br/>");
var memory = document.getElementById("memory"); // Get persistent element
memory.load("myPersistentData"); // Retrieve saved data by name
var user = memory.getAttribute("username"); // Query attributes
var color = memory.getAttribute("favoriteColor");

document.write(user + '; ' + color);
</script>
</body>
</html>

Tuesday, October 23, 2007

'document.getElementById(...)' 为空或不是对象


<div id="form_div"></div>
<script type="text/javascript">
var urls = 'http://www.google.com/search?q=test';
var fragment = document.createDocumentFragment();
var form = document.createElement('form');
var input = document.createElement('input');
var submit = document.createElement('input');
form.action = urls;
form.setAttribute('method', 'post'); // 这里不能设置为get方法,因为GET方法会将action中原有的参数过滤后加个表单里的参数,如text1=value。
input.setAttribute('value', "value");
input.setAttribute('type', "text");
input.setAttribute('name', "text1");
input.setAttribute('size', "50");
submit.setAttribute('type', "submit");
form.appendChild(input); // node.appendChild(newNode)方法执行后返回的值是newNode。
form.appendChild(document.createElement('br'));
form.appendChild(submit);
fragment.appendChild(form);
try
{
document.getElementById('form_div').appendChild(fragment);
}
catch (e)
{
document.write(e.message);
//document.getElementById("form_div") => null
//FF: document.getElementById("form_div") has no properties
//IE: 'document.getElementById(...)' 为空或不是对象
//document.write(e.description);
//IE: 'document.getElementById(...)' 为空或不是对象
}
</script>

必须将给以上代码写入body标签中才能正确运行。
不然这段代码在浏览器解析时生成的DOM中,这一段javascript被置于head中,而form_div这个Element则会出现在浏览器生成的DOM的body中,而页面js被执行时,因为这个Element在执行语句之后,所以就会找不到此Element,从而报对象为空或不是对象这个错误。

Monday, October 22, 2007

window.location and document.location

window.location 和 window.location.herf 为可读写的属性,对此赋值可定向页面去指定的URL。
document.location 和 document.URL 等价,是可只读属性,并且推荐使用document.URL,document.location 已废弃。不过多数浏览器还是可以对document.location 和 document.location.href 赋值定向到新的URL,此做法不推荐使用。

ntpdate error: No Server suitable for synchronization found

主要是ntpd server的iptables把udp的123端口关了,局域网内其他机器无法访问到Server,所以才会报No Server suitable for synchronization found这个错误。

打开此udp端口重启iptables后用/usr/sbin/ntpdate ntp-server-address; /sbin/hwclock -w命令即可,当然client端最好是做个Crontab定时跑一下这个命令,同步时间。

rpm查询文件所属的rpm包

$> rpm -qf /usr/bin/crontab
vixie-cron-4.1-66.1.el5

没找到crontab命令,可以用yum直接在线安装
$> yum install vixie-cron

Friday, October 19, 2007

Iframe src 属性说明及使用

在Google的一些应用网页里面Iframe用得相当频繁,配合ajax做用户交互,有些是将form提交到Iframe(form的target属性指向iframe的name,form的action提交后服务器返回的内容会在form的target所在的iframe中写入,这个使用方法与frameset页面中某帧的链接<a target="xxx" href="xxx">中指定target显示框架用法相同),再从ifrmae中取回数据显示给用户。

如test.html


<form action="form_action.html" method="post" target="target_iframe" accept-charset="utf-8">
<p><input type="hidden" name="var1" value="1" id="var1"></p>
<p><input type="hidden" name="var2" value="2" id="var2"></p>
<p><input type="submit" value="submit"></p>
</form>

<iframe src="http://www.baidu.com" id="iframe_id" name="target_iframe"></iframe>

和form_ation.html

<html>
<body>
<div id="div1">form action returned html body</div>
</body>
</html>

Thursday, October 18, 2007

[svn Error]svn: Valid UTF-8 data

$> svn up project_name
svn: Valid UTF-8 data
(hex: 31 30 31 38)
followed by invalid UTF-8 sequence
(hex: cd f8 d5 be)

对项目下面所有文件和文件夹逐一更新,发现有个目录里有二个文件因为文件名中有带中文字符导致此问题(应该GBK字符,项目是GBK的)。修改文件名后即解决此问题。

Usage of Ruby parseexcel lib

gem包安装后的README文件有个实例简单说明了这个lib的使用方法,gem包没有安装doc


#!/usr/bin/env ruby

require 'parseexcel'

# your first step is always reading in the file.
# that gives you a workbook-object, which has one or more worksheets,
# just like in Excel you have the possibility of multiple worksheets.
workbook = Spreadsheet::ParseExcel.parse(path_to_file)

# usually, you want the first worksheet:
worksheet = workbook.worksheet(0)

# now you can either iterate over all rows, skipping the first number of
# rows (in case you know they just contain column headers)
skip = 2
worksheet.each(skip) { |row|
# a row is actually just an Array of Cells..
first_cell = row.at(0)

# how you get data out of the cell depends on what datatype you
# expect:

# if you expect a String, you can pass an encoding and (iconv
# required) the content of the cell will be converted.
str = row.at(1).to_s('latin1')

# if you expect a Float:
float = row.at(2).to_f

# if you expect an Integer:
int = row.at(3).to_i

# if you expect a Date:
date = row.at(4).date

# ParseExcel makes a guess at what Datatype a cell has. At the moment,
# possible values are: :date, :numeric, :text
celltype = first_cell.type
}

# if you know exactly which row your data resides in, you may just
# retrieve that row, which is again simply an Array of Cells
row = worksheet.row(26)

Wednesday, October 17, 2007

window.onbeforeunload 使用说明


<script type="text/javascript">
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
document.write("<iframe src='http://www.google.com'></iframe>");
return message;
}
</script>

在IE中关闭前会弹confirm框同时后台会加载此iframe,但FireFox会有弹框提示但并不会加载iframe。

wget 使用技巧

wget 是一个命令行的下载工具。对于我们这些 Linux 用户来说,几乎每天都在使用它。下面为大家介绍几个有用的 wget 小技巧,可以让你更加高效而灵活的使用 wget。

1. $ wget -r -np -nd http://example.com/packages/

这条命令可以下载 http://example.com 网站上 packages 目录中的所有文件。其中,-np 的作用是不遍历父目录,-nd 表示不在本机重新创建目录结构。
2. $ wget -r -np -nd --accept=iso http://example.com/centos-5/i386/

与上一条命令相似,但多加了一个 --accept=iso 选项,这指示 wget 仅下载 i386 目录中所有扩展名为 iso 的文件。你也可以指定多个扩展名,只需用逗号分隔即可。
3. $ wget -i filename.txt

此命令常用于批量下载的情形,把所有需要下载文件的地址放到 filename.txt 中,然后 wget 就会自动为你下载所有文件了。
4. $ wget -c http://example.com/really-big-file.iso

这里所指定的 -c 选项的作用为断点续传。
5. $ wget -m -k (-H) http://www.example.com/

该命令可用来镜像一个网站,wget 将对链接进行转换。如果网站中的图像是放在另外的站点,那么可以使用 -H 选项。

原文网址:http://linuxtoy.org/archives/wget-tips.html(2007-10-14 Toy)

Rails APP Error : wrong argument type Mysql (expected Data)

主要是ActiveRecord和Mysql连接的问题,更新一下ActiveRecord就可以。
$> gem update rails -v 1.2.3

Tuesday, October 16, 2007

在安装ruby1.8.5和mysql-ruby2.7.5过程碰到的几个问题及解决方法


$> ruby extconf.rb --with-mysql-dir=/usr/local/mysql
can't find header files for ruby.

If you receive an error which contains "can’t find header files for ruby.", then please install the ruby-devel package.
wget ftp://ftp.nluug.nl/pub/os/Linux/distr/CentOS/5.0/os/x86_64/CentOS/ruby-devel-1.8.5-5.el5.i386.rpm

If you receive the error message "cannot restore segment prot after reloc: Permission denied" when launching IDL, then your SELinux configuration is preventing IDL from launching.

To rectify this issue, you can either:
* Change the default security context for IDL by issuing the command:
$> chcon -t texrel_shlib_t /usr/local/ruby/lib/ruby/site_ruby/1.8/i686-linux/mysql.so
* Disabling SELinux altogether by setting the line
SELINUX=disabled

Monday, October 15, 2007

JavaScript中的闭包closures简单说明

<script type="text/javascript">
uniqueID = (function() { // The call object of this function holds our value
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it, and return a function: function() { return id++; }

alert(uniqueID()); // alert(function() { return id++; }());
alert(uniqueID());
alert(uniqueID());
// JavaScript函数是将要执行的代码以及执行这些代码的作用域和作用域的arguments一起构成的一个综合体,即使函数包含相同的JavaScript代码,并且每段代码都是从相同的作用域调用的,还是可以返回不同的结果的。因为JavaScript中的函数是在当时定义它们的作用域里运行的,而不是在执行它们的作用域里运行的。这种代码和作用域的综合体叫闭包。所有的JavaScript函数都是闭包。
</script>

当一个嵌套函数被导出到它所定义的作用域外时,这种闭包才有意思。当一个嵌套的函数以这种方式使用时,通常被明确的叫做一个闭包。
uniqueID的函数体为function() { return id++; },它是从一个function literal中返回得到,并包含了导出后的作用域,包含了变量名和值等,也就是从这个匿名函数是返回了一个闭包。
在uniqueID被函数运算符()调用时,已经在函数定义的作用域外,所有调用操作会影响闭包内的变量并仍会被此闭包继续保存。

Ruby和Perl中有个lambda方法也可以生成一个闭包。

更多关于javascript的闭包说明请查看此处

Function() constructor of JavaScript

There are a few points that are important to understand about the Function() constructor:

The Function() constructor allows JavaScript code to be dynamically created and compiled at runtime. It is like the global eval() function (see Part III) in this way.

The Function() constructor parses the function body and creates a new function object each time it is called. If the call to the constructor appears within a loop or within a frequently called function, this process can be inefficient. By contrast, a function literal or nested function that appears within a loop or function is not recompiled each time it is encountered. Nor is a different function object created each time a function literal is encountered. (Although, as noted earlier, a new closure may be required to capture differences in the lexical scope in which the function is defined.)

A last, very important point about the Function() constructor is that the functions it creates do not use lexical scoping; instead, they are always compiled as if they were top-level functions, as the following code demonstrates:


var y = "global";
function constructFunction() {
var y = "local";
return new Function("return y"); // Does not capture the local scope!
}

// This line displays "global" because the function returned by the
// Function() constructor does not use the local scope. Had a function
// literal been used instead, this line would have displayed "local".
alert(constructFunction()()); // Displays "global"

JavaScript中函数function说明

从技术上说,function并非是一个语句。在JavaScript程序中,语名会引发动态的行为,但是函数定义描述的却是静态的程序结构。语句是在运行时执行的,而函数是在实际运行之前,浏览器载入JavaScript的时候被解析的,或者说是在被编译时定义了这个函数。当Javascript解析程序遇到一个函数定义时,它就解析并存储(而不执行)构成函数主体的语句,然后定义一个和该函数同名的属性(如果函数定义嵌套在其他函数中,那么就在调用对象中定义这个属性,否则在全局对象中定义这个属性)以保存它。
The fact that function definitions occur at parse time rather than at runtime causes some surprising effects. Consider the following code:
<script type="text/javascript">
alert(f(4)); // Displays 16. f( ) can be called before it is defined.
var f = 0; // This statement overwrites the property f.
function f(x) { // This "statement" defines the function f before either
return x*x; // of the lines above are executed.
}
alert(f); // Displays 0. f( ) has been overwritten by the variable f.
</script>
另外如果Ajax调用返回的内容包含JS的话,需要对JS进行eval()操作,才能获取到JS中的变量和方法,其中方法必须以Function Literals直接量的方式赋个一个变量才能获得此方法。另外Ajax载入的JS中变量都要以全局变量方式载入才能得到,即变量前不能加var声明。
Function内部语句发变量定义如果不加var声明的话,只要function被执行过,此变量也会成为一个全局变量。