获取FCKeditor编辑器内容的值

答案原址:http://www.phpchina.com/html/97/n-33197.html
利用Javascript取和设FCKeditor值也是非常容易的,如下:

EditorName是页面中可编辑区域元素的id比如:
<TEXTAREA id="texterea1" name="content" rows="30" cols="420"><c:out value="${content}"/></TEXTAREA>
EditorName就是texterea1了

// 获取编辑器中HTML内容
function getEditorHTMLContents(EditorName) {
var oEditor = FCKeditorAPI.GetInstance(EditorName);
return(oEditor.GetXHTML(true));
}

// 获取编辑器中文字内容
function getEditorTextContents(EditorName) {
var oEditor = FCKeditorAPI.GetInstance(EditorName);
return(oEditor.EditorDocument.body.innerText);
}

// 设置编辑器中内容
function SetEditorContents(EditorName, ContentStr) {
var oEditor = FCKeditorAPI.GetInstance(EditorName) ;
oEditor.SetHTML(ContentStr) ;
}

FCKeditorAPI是FCKeditor加载后注册的一个全局对象,利用它我们就可以完成对编辑器的各种操作。

《Head First 设计模式》php设计模式版

策略模式

 

<?php
/**
 * 策略模式
 * 定义了算法族,分别封装起来,让它们之间可以互相替换,
 * 此模式让算法的变化独立于使用算法的客户。
 */
//飞行行为接口
interface FlyBehavior {
    public function fly();
}
//呱呱叫行为接口
interface QuackBehavior {
    public function quack();
}
//翅膀飞行
class FlyWithWings implements FlyBehavior {
    public function fly() {
        echo "I'm flying!!\n";
    }
}
//不会飞
class FlyNoWay implements FlyBehavior {
    public function fly() {
        echo "I can't fly!\n";
    }
}
class FlyRocketPowered implements FlyBehavior {
    public function fly() {
        echo "I'm flying with a rocket!\n";
    }
}
class Qquack implements QuackBehavior {
    public function quack() {
        echo "Quack\n";
    }
}
class Squeak implements QuackBehavior {
    public function quack() {
        echo "Squeak\n";
    }
}
class MuteQuack implements QuackBehavior {
    public function quack() {
        echo "<< Silence >>\n";
    }
}
abstract class Duck {
    protected $quack_obj;
    protected $fly_obj;
    public abstract function display();

    public function performQuack() {
        $this->quack_obj->quack();
    }
    public function performFly() {
        $this->fly_obj->fly();
    }
    public function swim() {
        echo "All ducks float, even decoys!\n";
    }
    public function setFlyBehavior(FlyBehavior $fb) {
        $this->fly_obj = $fb;
    }
    public function setQuackBehavior(QuackBehavior $qb) {
        $this->quack_obj = $qb;
    }
}

class ModelDuck extends Duck {
    public function __construct() {
        $this->fly_obj = new FlyNoWay();
        $this->quack_obj = new MuteQuack();
    }
    public function display() {
        echo "I'm a model duck!\n";
    }
}

$model = new ModelDuck();
$model->performFly();
$model->performQuack();
//提供新的能力
$model->setFlyBehavior(new FlyRocketPowered());
$model->setQuackBehavior(new Squeak());
$model->performFly();
$model->performQuack();

?>

 

单件模式

 

<?php
/**
 * 单件模式
 * 确保一个类只有一个实例,并提供一个全局访问点。
 */
class MyClass {
    private static $uniqueInstance;
    private function __construct() {

    }
    public static function getInstance() {
        if (self::$uniqueInstance == null) {
            self::$uniqueInstance = new MyClass();
        }
        return self::$uniqueInstance;
    }
}
$myClass = MyClass::getInstance();
var_dump($myClass);
$myClass = MyClass::getInstance();
var_dump($myClass);
?>

 

工厂方法模式

 

<?php
abstract class PizzaStore {
    public function orderPizza($type) {
        $pizza = $this->createPizza($type);

        $pizza->prepare();
        $pizza->bake();
        $pizza->cut();
        $pizza->box();
        return $pizza;
    }

    public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new NYStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new NYStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new NYStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new NYStylePapperoniPizza();
        } else {
            return null;

        }
    }
}
class ChicagoPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new ChicagoStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new ChicagoStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new ChicagoStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new ChicagoStylePapperoniPizza();
        } else {
            return null;
        }
    }
}
abstract class Pizza {
    public $name;
    public $dough;
    public $sauce;
    public $toppings = array();

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        echo "Yossing dough...\n";
        echo "Adding sauce...\n";
        echo "Adding toppings: \n";
        for ($i = 0; $i < count($this->toppings); $i++) {
            echo "    " . $this->toppings[$i] . "\n";
        }
    }

    public function bake() {
        echo "Bake for 25 minutes at 350\n";
    }

    public function cut() {
        echo "Cutting the pizza into diagonal slices\n";
    }

    public function box() {
        echo "Place pizza in official PizzaStore box\n";
    }

    public function getName() {
        return $this->name;
    }
}

class NYStyleCheesePizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and cheese Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano Cheese";
    }
}

class NYStyleVeggiePizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and veggie Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano veggie";
    }
}
class NYStyleClamPizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and clam Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano clam";
    }
}
class NYStylePapperoniPizza extends Pizza {
    public function __construct() {
        $this->name = "NY Style Sauce and papperoni Pizza";
        $this->dough = "Thin Crust Dough";
        $this->sauce = "Marinara Sauce";

        $this->toppings[] = "Grated Reggiano papperoni";
    }
}

class ChicagoStyleCheesePizza extends Pizza {
    public function __construct() {
        $this->name = "Chicago Style Deep Dish Cheese Pizza";
        $this->dough = "Extra Thick Crust Dough";
        $this->sauce = "Plum Tomato Sauce";

        $this->toppings[] = "Shredded Mozzarella Cheese";
    }

    public function cut() {
        echo "Cutting the pizza into square slices\n";
    }
}

$myStore = new NYPizzaStore();
$chicagoStore = new ChicagoPizzaStore();
$pizza = $myStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

$pizza = $chicagoStore->orderPizza("cheese");
echo "Ethan ordered a " . $pizza->getName() . "\n";

?>

 

工厂模式

 

<?php
abstract class PizzaStore {
    public function orderPizza($type) {
        $pizza = $this->createPizza($type);

        $pizza->prepare();
        $pizza->bake();
        $pizza->cut();
        $pizza->box();
        return $pizza;
    }

    public abstract function createPizza($type);
}
class NYPizzaStore extends PizzaStore {
    public function createPizza($type) {
        $pizza = null;
        $ingredientFactory = new NYPizzaIngredientFactory();
        if ($type == "cheese") {
            $pizza = new CheesePizza($ingredientFactory);
            $pizza->setName('New York Style Cheese Pizza');
        } elseif ($type == "veggie") {
            $pizza = new VeggiePizza($ingredientFactory);
            $pizza->setName('New York Style Veggie Pizza');
        } elseif ($type == "clam") {
            $pizza = new ClamPizza($ingredientFactory);
            $pizza->setName('New York Style Clam Pizza');
        } elseif ($type == "papperoni") {
            $pizza = new PapperoniPizza($ingredientFactory);
            $pizza->setName('New York Style Papperoni Pizza');
        }
        return $pizza;
    }
}
class ChicagoPizzaStore extends PizzaStore {
    public function createPizza($type) {
        if ($type == "cheese") {
            return new ChicagoStyleCheesePizza();
        } elseif ($type == "veggie") {
            return new ChicagoStyleVeggiePizza();
        } elseif ($type == "clam") {
            return new ChicagoStyleClamPizza();
        } elseif ($type == "papperoni") {
            return new ChicagoStylePapperoniPizza();
        } else {
            return null;
        }
    }
}
interface PizzaIngredientFactory {
    public function createDough();
    public function createSauce();
    public function createCheese();
    public function createVeggies();
    public function createPepperoni();
    public function createClam();
}
class NYPizzaIngredientFactory implements PizzaIngredientFactory {
    public function createDough() {
        return new ThinCrustDough();
    }
    public function createSauce() {
        return new MarinaraSauce();
    }
    public function createCheese() {
        return new ReggianoCheese();
    }
    public function createVeggies() {
        $veggies = array(
        new Garlic(),
        new Onion(),
        new Mushroom(),
        new RedPepper(),
        );
        return $veggies;
    }
    public function createPepperoni() {
        return new SlicedPepperoni();
    }
    public function createClam() {
        return new FreshClams();
    }
}
class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory {
    public function createDough() {
        return new ThickCrustDough();
    }
    public function createSauce() {
        return new PlumTomatoSauce();
    }
    public function createCheese() {
        return new Mozzarella();
    }
    public function createVeggies() {
        $veggies = array(
        new BlackOlives(),
        new Spinach(),
        new EggPlant(),
        );
        return $veggies;
    }
    public function createPepperoni() {
        return new SlicedPepperoni();
    }
    public function createClam() {
        return new FrozenClams();
    }
}
abstract class Pizza {
    public $name;
    public $dough;
    public $sauce;
    public $veggies = array();
    public $cheese;
    public $pepperoni;
    public $clam;

    public abstract function prepare();

    public function bake() {
        echo "Bake for 25 minutes at 350\n";
    }

    public function cut() {
        echo "Cutting the pizza into diagonal slices\n";
    }

    public function box() {
        echo "Place pizza in official PizzaStore box\n";
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function __toString() {

    }
}

class CheesePizza extends Pizza {
    public $ingredientFactory;

    public function __construct(PizzaIngredientFactory $ingredientFactory) {
        $this->ingredientFactory = $ingredientFactory;
    }

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        $this->dough = $this->ingredientFactory->createDough();
        $this->sauce = $this->ingredientFactory->createSauce();
        $this->cheese = $this->ingredientFactory->createCheese();
    }
}

class ClamPizza extends Pizza {
    public $ingredientFactory;

    public function __construct(PizzaIngredientFactory $ingredientFactory) {
        $this->ingredientFactory = $ingredientFactory;
    }

    public function prepare() {
        echo "Preparing " . $this->name . "\n";
        $this->dough = $this->ingredientFactory->createDough();
        $this->sauce = $this->ingredientFactory->createSauce();
        $this->cheese = $this->ingredientFactory->createCheese();
        $clam = $this->ingredientFactory->createClam();
    }
}

$nyPizzaStore = new NYPizzaStore();
$nyPizzaStore->orderPizza('cheese');
?>

 

观察者模式

 

<?php
/**
 * 观察者模式
 * 定义了对象之间的一对多依赖,当一个对象改变状态时,
 * 它的所有依赖者都会收到通知并自动更新。
 */
interface Subject {
    public function registerObserver(Observer $o);
    public function removeObserver(Observer $o);
    public function notifyObservers();
}
interface Observer {
    public function update($temperature, $humidity, $pressure);
}
interface DisplayElement {
    public function display();
}
class WeatherData implements Subject {
    private $observers = array();
    private $temperature;
    private $humidity;
    private $pressure;
    public function __construct() {
        $this->observers = array();
    }
    public function registerObserver(Observer $o) {
        $this->observers[] = $o;
    }
    public function removeObserver(Observer $o) {
        if (($key = array_search($o, $this->observers)) !== false) {
            unset($this->observers[$key]);
        }
    }
    public function notifyObservers() {
        foreach ($this->observers as $observer) {
            $observer->update($this->temperature, $this->humidity, $this->pressure);
        }
    }
    public function measurementsChanged() {
        $this->notifyObservers();
    }
    public function setMeasurements($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->pressure = $pressure;
        $this->measurementsChanged();
    }
}
class CurrentConditionsDisplay implements Observer, DisplayElement {
    private $temperature;
    private $humidity;
    private $weatherData;
    public function __construct(Subject $weatherData) {
        $this->weatherData = $weatherData;
        $weatherData->registerObserver($this);
    }
    public function update($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->display();
    }
    public function display() {
        echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%\n";
    }
}
class StatistionsDisplay implements Observer, DisplayElement {
    private $temperature;
    private $humidity;
    private $pressure;
    private $weatherData;
    public function __construct(Subject $weatherData) {
        $this->weatherData = $weatherData;
        $weatherData->registerObserver($this);
    }
    public function update($temperature, $humidity, $pressure) {
        $this->temperature = $temperature;
        $this->humidity = $humidity;
        $this->pressure = $pressure;
        $this->display();
    }
    public function display() {
        echo "温度:" . $this->temperature . "; 湿度:" . $this->humidity . "%; 气压:" . $this->pressure . "\n";
    }
}
$weatherData = new WeatherData();
$currentDisplay = new CurrentConditionsDisplay($weatherData);
$statistionDisplay = new StatistionsDisplay($weatherData);
$weatherData->setMeasurements(10, 20, 30);
$weatherData->removeObserver($currentDisplay);
$weatherData->setMeasurements(30, 40, 50);
?>

 

命令模式

 

<?php

class Light {
    public function __construct() {

    }

    public function on() {
        echo "Light On\n";
    }

    public function off() {
        echo "Light Off\n";
    }
}

interface Command {
    public function execute();
}

class LightOnCommand implements Command {
    public $light;

    public function __construct(Light $light) {
        $this->light = $light;
    }

    public function execute() {
        $this->light->on();
    }
}

class SimpleRemoteControl {
    public $slot;

    public function __construct() {

    }

    public function setCommand(Command $command) {
        $this->slot = $command;
    }

    public function buttonWasPressed() {
        $this->slot->execute();
    }
}

class RemoteControlTest {
    public static function main() {
        $remote = new SimpleRemoteControl();
        $light = new Light();
        $lightOn = new LightOnCommand($light);
        $remote->setCommand($lightOn);
        $remote->buttonWasPressed();
    }
}

RemoteControlTest::main();

?>

 

装饰者模式

 

<?php
/**
* 装饰着模式
* 动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
*/
abstract class Beverage {
public $description = "Unknown Beverage";

public function getDescription() {
return $this->description;
}

public abstract function cost();
}

abstract class CondimentDecorator extends Beverage {
//JAVA代码里这里是个抽象类,PHP不允许这么做
public function getDescription() {
return $this->description;
}
}

class Espresso extends Beverage {
public function __construct() {
$this->description = "Espresso";
}

public function cost() {
return 1.99;
}
}

class HouseBlend extends Beverage {
public function __construct() {
$this->description = "HouseBlend";
}

public function cost() {
return .89;
}
}

class DarkRoast extends Beverage {
public function __construct() {
$this->description = "DarkRoast";
}

public function cost() {
return .99;
}
}

class Mocha extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Mocha";
}
public function cost() {
return .20 + $this->beverage->cost();
}
}

class Whip extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Whip";
}
public function cost() {
return .10 + $this->beverage->cost();
}
}

class Soy extends CondimentDecorator {
public $beverage;

public function __construct(Beverage $beverage) {
$this->beverage = $beverage;
}
public function getDescription() {
return $this->beverage->getDescription() . ", Soy";
}
public function cost() {
return .15 + $this->beverage->cost();
}
}

$beverage = new Espresso();
echo $beverage->getDescription() . "\n";
$beverage2 = new DarkRoast();
$beverage2 = new Mocha($beverage2);
$beverage2 = new Mocha($beverage2);
$beverage2 = new Whip($beverage2);
echo $beverage2->getDescription() . " $" . $beverage2->cost() . "\n";

$beverage3 = new HouseBlend();
$beverage3 = new Soy($beverage3);
$beverage3 = new Mocha($beverage3);
$beverage3 = new Whip($beverage3);
echo $beverage3->getDescription() . " $" . $beverage3->cost() . "\n";
?>

状态模式

 

<?php

class GumballMachine {
const SOLD_OUT = 0;
const NO_QUARTER = 1;
const HAS_QUARTER = 2;
const SOLD = 3;

public $state = self::SOLD_OUT;
public $count = 0;

public function __construct($count) {
$this->count = $count;
if ($count > 0) {
$this->state = self::NO_QUARTER;
}
}

public function insertQuarter() {
if ($this->state == self::HAS_QUARTER) {
echo "You can't insert another quarter!\n";
} else if ($this->state == self::NO_QUARTER) {
$this->state = self::HAS_QUARTER;
echo "You inserted a quarter!\n";
} else if ($this->state == self::SOLD_OUT) {
echo "You can't insert a quarter, the machine is sold out!\n";
} else if ($this->state == self::SOLD) {
echo "Please wait, we're already giving you a gumball!\n";
}
}
}

$obj = new GumballMachine(0);
print_r($obj)

?>

文本操作类

 

<?php 

class CtbClass { 

var $file; 

var $index; 

//建立一个文件并写入输入 

function null_write($new) 

$f=fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$new); 

fclose($f); 

// 添加数据记录到文件末端 

function add_write($new) { 

$f=fopen($this->file,"a"); 

flock($f,LOCK_EX); 

fputs($f,$new); 

fclose($f); 

// 配合readfile()的返回一起使用,把一行数据转换为一维数组 

function make_array($line) { 

$array = explode("\x0E",$line); 

return $array; 

//把为一维数组转换一行数据 

function join_array($line) { 

$array = join("\x0E",$line); 

return $array; 

// 返回数据文件的总行数 

function getlines() { 

$f=file($this->file); 

return count($f); 

// 返回下一行的数据记录(备用) 

function next_line() { 

$this->index=$this->index++; 

return $this->get(); 

// 返回上一行的数据记录(备用) 

function prev_line() { 

$this->index=$this->index--; 

return $this->get(); 

// 返回当前行的数据记录数据较小 

function get() { 

$f=fopen($this->file,"r"); 

flock($f,LOCK_SH); 

for($i=0;$i<=$this->index;$i++) { 

$rec=fgets($f,1024); 

$line=explode("\x0E",$rec); 

fclose($f); 

return $line; 

// 返回当前行的数据记录数据较大 

function get_big_file() { 

$f=fopen($this->file,"r"); 

flock($f,LOCK_SH); 

for($i=0;$i<=$this->index;$i++) { 

$rec=fgets($f,1024*5); 

$line=explode("\x0E",$rec); 

fclose($f); 

return $line; 

// 打开数据文件---以一维数组返回文件内容 

function read_file() { 

if (file_exists($this->file)) { 

$line =file($this->file); 

return $line; 

// 打开数据文件---以二维数组返回文件内容 

function openFile() { 

if (file_exists($this->file)) { 

$f =file($this->file); 

$lines = array(); 

foreach ($f as $rawline) { 

$tmpline = explode("\x0E",$rawline); 

array_push($lines, $tmpline); 

return $lines; 

// 传入一个数组,合并成一行数据,重写整个文件 

function overwrite($array){ 

$newline = implode("\x0E",$array); 

$f = fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newline); 

fclose($f); 

// 添加一行数据记录到文件末端 

function add_line($array,$check_n=1) { 

$s=implode("\x0E",$array); 

$f=fopen($this->file,"a"); 

flock($f,LOCK_EX); 

fputs($f,$s); 

if ($check_n==1) fputs($f,"\n"); 

fclose($f); 

// 插入一行数据记录到文件最前面 

function insert_line($array) { 

$newfile = implode("\x0E",$array); 

$f = fopen($this->file,"r"); 

flock($f,LOCK_SH); 

while ($line = fgets($f,1024)) { 

$newfile .= $line; 

fclose($f); 

$f = fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newfile); 

fclose($f); 

// 更新所有符合条件的数据记录,适用于每行字节数据较大的情况 

function update($column,$query_string,$update_array) { 

$update_string = implode("\x0E",$update_array); 

$newfile = ""; 

$fc=file($this->file); 

$f=fopen($this->file,"r"); 

flock($f,LOCK_SH); 

for ($i=0;$i<count($fc);$i++) { 

$list = explode("\x0E",$fc[$i]); 

if ($list[$column] != $query_string) { 

$newfile = $newfile.chop($fc[$i])."\n"; 

} else { 

$newfile = $newfile.$update_string; 

fclose($f); 

$f=fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newfile); 

fclose($f); 

// 更新所有符合条件的数据记录,适用于每行字节数据较小的情况 

function update2($column,$query_string,$update_array) { 

$newline = implode("\x0E",$update_array); 

$newfile = ""; 

$f = fopen($this->file,"r"); 

flock($f,LOCK_SH); 

while ($line = fgets($f,1024)) { 

$tmpLine = explode("\x0E",$line); 

if ($tmpLine[$column] == $query_string) { 

$newfile .= $newline; 

} else { 

$newfile .= $line; 

fclose($f); 

$f = fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newfile); 

fclose($f); 

// 删除所有符合条件的数据记录,适用于每行字节数据较大的情况 

function delete($column,$query_string) { 

$newfile = ""; 

$fc=file($this->file); 

$f=fopen($this->file,"r"); 

flock($f,LOCK_SH); 

for ($i=0;$i<count($fc);$i++) { 

$list = explode("\x0E",$fc[$i]); 

if ($list[$column] != $query_string) { 

$newfile = $newfile.chop($fc[$i])."\n"; 

fclose($f); 

$f=fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newfile); 

fclose($f); 

// 删除所有符合条件的数据记录,适用于每行字节数据较小的情况 

function delete2($column,$query_string){ 

$newfile = ""; 

$f = fopen($this->file,"r"); 

flock($f,LOCK_SH); 

while ($line = fgets($f,1024)) { 

$tmpLine = explode("\x0E",$line); 

if ($tmpLine[$column] != $query_string) { 

$newfile .= $line; 

fclose($f); 

$f = fopen($this->file,"w"); 

flock($f,LOCK_EX); 

fputs($f,$newfile); 

fclose($f); 

//取得一个文件里某个字段的最大值 

function get_max_value($column) { 

$tlines = file($this->file); 

for ($i=0;$i<=count($tlines);$i++) { 

$line=explode("\x0E",$tlines[$i]); 

$get_value[]=$line[$column]; 

$get_max_value = max($get_value); 

return $get_max_value; 

 

// 根据数据文件的某个字段是否包含$query_string进行查询,以二维数组返回所有符合条件的数据 

function select($column, $query_string) { 

$tline = $this->openfile(); 

$lines = array(); 

foreach ($tline as $line) { 

if ($line[$column] == $query_string) { 

array_push($lines, $line); 

return $lines; 

// 功能与function select()一样,速度可能略有提升 

function select2($column, $query_string) { 

if (file_exists($this->file)) { 

$tline = $this->read_file(); 

foreach ($tline as $tmpLine) { 

$line = $this->make_array($tmpLine); 

if ($line[$column] == $query_string) { 

$lines[]=$tmpLine; 

return $lines; 

// 根据数据文件的某个字段是否包含$query_string进行查询,以一维数组返回第一个符合条件的数据 

function select_line($column, $query_string) { 

$tline = $this->read_file(); 

foreach ($tline as $tmpLine) { 

$line = $this->make_array($tmpLine); 

if ($line[$column] == $query_string) { 

return $line; 

break; 

// select next/prev line(next_prev ==> 1/next, 2/prev) by cx 

function select_next_prev_line($column, $query_string, $next_prev) { 

$tline = $this->read_file(); 

$line_key_end = count($tline) - 1; 

$line_key = -1; 

foreach ($tline as $tmpLine) { 

$line_key++; 

$line = $this->make_array($tmpLine); 

if ($next_prev == 1) { // next? 

if ($line[$column] == $query_string) { 

if ($line_key == 0) { 

return 0; 

} else { 

$line_key_up = $line_key - 1; 

return $up_line; 

} else { 

$up_line = $line; 

} elseif ($next_prev == 2) { // prev? 

if ($line[$column] == $query_string) { 

if ($line_key == $line_key_end) { 

return 0; 

} else { 

$line_key_down = $line_key + 1; 

break; 

} else { 

return 0; 

$down_line = $this->make_array($tline[$line_key_down]); 

return $down_line; 

 

?>

jQuery ready vs load

jQuery ready vs load

在使用Javascript操作HTML DOM時,記得要養成網頁載入後才動手的好習慣,不然會有可怕的事發生… (可參考邊做邊學 jQeury 系列 3-jQuery 常用的 Javascript 技巧教學影片,在5分02秒的示範)

在jQuery中,要做到"等網頁載入後再執行",我們有兩種選擇:

$(document).ready(fn)與$(window).load(fn)

二者的差別在於$(document).ready(fn)發生在"網頁本身的HTML"載入後就觸發,而$(window).load(fn)則會等到"網頁HTML標籤中引用的圖檔、內嵌物件(如Flash)、IFrame"等拉哩拉雜的東西都載入後才會觸發。

我 寫了一段示範程式突顯二者的區別。由於Sky_angmap_4.jpg是一張1.2MB的大型圖檔,實際執行時,可以觀察到 “ready event!” –> 圖檔緩慢顯現 -> "load event!”的過程。(嫌下載時間太短,差別不夠明顯的話,可以試試Sky_angmap_7.jpg,XD)

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title></title>
    <script type="text/javascript"
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js">
    </script>
    <script type="text/javascript">
        $(function() {
            alert("ready event!");
        });
        $(window).load(function() {
            alert("load event!");
        });
    </script>
</head>
<body>
<img src="http://blender-archi.tuxfamily.org/images/Sky_angmap_4.jpg" />
</body>
</html>


一般來說,等網頁全部元素都載入才執行程式時機有點晚,因為在此之前,使用者已經可以點選操作網頁,跳脫我們程式的掌控範圍。因此,我們幾乎都是將 程式放在$(document).read(function() { ... })中(即$(function() { … }))。

$(window).load(fn)適合執行一些要等待圖檔或元素全部載入才可進行的動作,例如: 檢查圖檔長寬。換句話說,上回的大圖自動縮小Script可以透過$(window).load(fn)改寫得更簡單,完全不用擔心圖檔沒下載完成時的特殊處理,算是一個很好的應用範例。

排版顯示純文字複製文字

    function GM_wait() {
        if(typeof unsafeWindow.jQuery == 'undefined') 
            window.setTimeout(GM_wait,100);
        else 
        { 
            $ = unsafeWindow.jQuery; 
            $(window).load(resizeHugeImage);
        }
    }
    GM_wait();
 
    // All your GM code must be inside this function
    function resizeHugeImage() {
        $("img").each(function() {
            var img = $(this);
            var w = img.width(), h = img.height();
            var longSide = (w > h ? w : h);
    //...以下省略...

理解JavaScript中的arguments,callee,caller,apply

arguments

该对象代表正在执行的函数和调用它的函数的参数。

[function.]arguments[n]
参数function :选项。当前正在执行的 Function 对象的名字。 n :选项。要传递给 Function 对象的从0开始的参数值索引。
说明

Arguments是进行函数调用 时,除了指定的参数外,还另外创建的一个隐藏对象。Arguments是一个类似数组但不是数组的对象,说它类似数组是因为其具有数组一样的访问性质及方 式,可以由arguments[n]来访问对应的单个参数的值,并拥有数组长度属性length。还有就是arguments对象存储的是实际传递给函数 的参数,而不局限于函数声明所定义的参数列表,而且不能显式创建 arguments 对象。arguments 对象只有函数开始时才可用。

<html>
<head><title>test-apply&call</title></head>
<body>
<script type="text/javascript">
//<![CDATA[
function ArgTest(a, b){
   var i, s = "The ArgTest function expected ";
   var numargs = arguments.length;
arguments.length即为这个函数调用时所带的参数数量     // 获取被传递参数的数值。  //ArgTest('a','b'):numargs=2, expargs=2
   var expargs = ArgTest.length;
;ArgTest.length为函数规定的参数数量         // 获取期望参数的数值。//ArgTest('a','b','c'):numargs=3, expargs=2
   if (expargs < 2)
      s += expargs + " argument. ";
   else
      s += expargs + " arguments. ";
   if (numargs < 2)
      s += numargs + " was passed.";
   else
      s += numargs + " were passed.";
   s += "/n/n"
   for (i =0 ; i < numargs; i++){      // 获取参数内容。
   s += " Arg " + i + " = " + arguments[i] + "/n";
;arguments类似数组 可通过arguments[ ]进行取得各个参数值
   }
   return(s);                          // 返回参数列表。
}

window.document.write(ArgTest('aaa', 'bbbb','cccc','dddd'));
//]]>
</script>

 

caller    [召唤者]
返回一个对函数的引用,该函数调用了当前函数。
    functionName.caller
    functionName 对象是所执行函数的名称。
说明
对 于函数来说,caller属性只有在函数执行时才有定义。如果函数是由顶层调用的,那么 caller包含的就是 null 。如果在字符串上下文中使用 caller属性,那么结果和 functionName.toString 一样,也就是说,显示的是函数的反编译文本。
下面的例子说明了 caller 属性的用法:// caller demo {
function callerDemo() {
    if (callerDemo.caller) {
        var a= callerDemo.caller.toString();
          alert(a);
      } else {
          alert("this is a top function");
      }
}
function handleCaller() {
      callerDemo();
}

handleCaller()时候,返回function handleCaller() { callerDemo();}【即callerDemo()返回用它的的函数的本身的String形式】,如果直接运行callerDemo(),返回function anonymous(){callerDemo();}

 

callee   

返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文。[function.]arguments.callee可选项 function参数是当前正在执行的 Function对象的名称。说明callee属性的初始值就是正被执行的 Function 对象。callee属性是 arguments 对象的一个成员,它表示对函数对象本身的引用,这有利于匿名
函数的递归或者保证函数的封装性,例如下边示例的递归计算1到n的自然数之和。而该属性
仅当相关函数正在执行时才可用。还有需要注意的是callee拥有length属性,这个属性有时候
用于验证还是比较好的。arguments.length是实参长度,arguments.callee.length是
形参长度,由此可以判断调用时形参长度是否和实参长度一致。示例//callee可以打印其本身
function calleeDemo() {
      alert(arguments.callee);
}

//calleeDemo() 就返回calleeDemo() 函数本身的String形式:function calleeDemo() { alert(arguments.callee);}
//用于验证参数
function calleeLengthDemo(arg1, arg2) {
    if (arguments.length==arguments.callee.length) {
          window.alert("验证形参和实参长度正确!");
        return;
      } else {
          alert("实参长度:" +arguments.length);//实际使用calleeLengthDemo(arg1, arg2)函数所带的参数:calleeLengthDemo('a') 则实参为1
          alert("形参长度: " +arguments.callee.length);//calleeLengthDemo(arg1, arg2)函数所定义的参数数:2
      }
}
//递归计算
var sum = function(n){
  if (n <= 0)                       
  return 1;
  else
    return n + arguments.callee(n - 1)// arguments.callee调用当前正在执行的函数,即sum本身!
}比较一般的递归函数:var sum = function(n){
    if (1==n) return 1;
    else return n + sum (n-1);
}调用时:alert(sum(100));
其中函数内部包含了对sum自身的引用,函数名仅仅是一个变量名,在函数内部调用sum即相当于调用
一个全局变量,不能很好的体现出是调用自身,这时使用callee会是一个比较好的方法。
callee可以打印本身

call和apply

  它们的作用都是将函数绑定到另外一个对象上去运行两者仅在定义参数方式有所区别:      apply(thisArg,argArray);      call(thisArg[,arg1,arg2…] ]);
即所有函数内部的this指针都会被赋值为thisArg,这可实现将函数作为另外一个对象的方法运行的目的
apply的说明如果 argArray不是一个有效的数组或者不是 arguments对象,那么将导致一个 TypeError。
如果没有提供 argArray和 thisArg任何一个参数,那么 Global 对象将被用作 thisArg,
并且无法被传递任何参数。
call的说明call方法可将一个函数的对象上下文从初始的上下文改变为由 thisArg指定的新对象。
如果没有提供 thisArg参数,那么 Global 对象被用作 thisArg相关技巧:应用call和apply还有一个技巧在里面,就是用call和apply应用另一个函数(类)以后,当前的
函数(类)就具备了另一个函数(类)的方法或者是属性,这也可以称之为“继承”。看下面示例:// 继承的演示
function base() {
    this.member = " dnnsun_Member";
    this.method = function() {
          window.alert(this.member);
      }
}
function extend() {
      base.call(this);
      window.alert(member);
      window.alert(this.method);
}
//调用 extend()后,window.alert(member)=》dnnsun_Memberwindow.alert(this.method)=》function (){window.alert(this.menber);}

上面的例子可以看出,通过call之后,extend可以继承到base的方法和属性。顺便提一下,在javascript框架prototype里就使用apply来创建一个定义类的模式,其实现代码如下:
var Class = {
    create: function() {
    return function() {
      this.initialize.apply(this, arguments);
      }
    }

}解析:从代码看,该对象仅包含一个方法:Create,其返回一个函数,即类。但这也同时是类的
构造函数,其中调用initialize,而这个方法是在类创建时定义的初始化函数。通过如此途径,
就可以实现prototype中的类创建模式示例:var vehicle=Class.create();
vehicle.prototype={
      initialize:function(type){
        this.type=type;
      }
      showSelf:function(){
          alert("this vehicle is "+ this.type);
      }
} var moto=new vehicle("Moto");
moto.showSelf();

javascript代码整理(多且精)

一、验证类
1、数字验证内
  1.1 整数
      /^(-|\+)?\d+$/.test(str)
  1.2 大于0的整数 (用于传来的ID的验证)
      /^\d+$/.test(str)
  1.3 负整数的验证
      /^-\d+$/.test(str)
2、时间类
  2.1 短时间,形如 (13:04:06)
      function isTime(str)
      {
        var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
        if (a == null) {alert('输入的参数不是时间格式'); return false;}
        if (a[1]>24 || a[3]>60 || a[4]>60)
        {
          alert("时间格式不对");
          return false
        }
        return true;
      }
  2.2 短日期,形如 (2003-12-05)
      function strDateTime(str)
      {
         var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
         if(r==null)return false;
         var d= new Date(r[1], r[3]-1, r[4]);
         return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
      }
  2.3 长时间,形如 (2003-12-05 13:04:06)
      function strDateTime(str)
      {
        var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
        var r = str.match(reg);
        if(r==null)return false;
        var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
        return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
      }
  2.4 只有年和月。形如(2003-05,或者2003-5)
  2.5 只有小时和分钟,形如(12:03)
3、表单类
  3.1 所有的表单的值都不能为空
      <input onblur="if(this.value.replace(/^\s+|\s+$/g,'')=='')alert('不能为空!')">
  3.2 多行文本框的值不能为空。
  3.3 多行文本框的值不能超过sMaxStrleng
  3.4 多行文本框的值不能少于sMixStrleng
  3.5 判断单选框是否选择。
  3.6 判断复选框是否选择.
  3.7 复选框的全选,多选,全不选,反选
  3.8 文件上传过程中判断文件类型
4、字符类
  4.1 判断字符全部由a-Z或者是A-Z的字字母组成
      <input onblur="if(/[^a-zA-Z]/g.test(this.value))alert('有错')">
  4.2 判断字符由字母和数字组成。
      <input onblur="if(/[^0-9a-zA-Z]/g.test(this.value))alert('有错')">
  4.3 判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
      /^([a-zA-z_]{1})([\w]*)$/g.test(str)
  4.4 字符串替换函数.Replace();
5、浏览器类
  5.1 判断浏览器的类型
      window.navigator.appName
  5.2 判断ie的版本
      window.navigator.appVersion
  5.3 判断客户端的分辨率
      window.screen.height;  window.screen.width;
 
6、结合类
  6.1 email的判断。
      function ismail(mail)
      {
        return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
      }
  6.2 手机号码的验证
  6.3 身份证的验证
      function isIdCardNo(num)
      {
        if (isNaN(num)) {alert("输入的不是数字!"); return false;}
        var len = num.length, re;
        if (len == 15)
          re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
        else if (len == 18)
          re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d)$/);
        else {alert("输入的数字位数不对!"); return false;}
        var a = num.match(re);
        if (a != null)
        {
          if (len==15)
          {
            var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]);
            var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
          }
          else
          {
            var D = new Date(a[3]+"/"+a[4]+"/"+a[5]);
            var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
          }
          if (!B) {alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false;}
        }
        return true;
      }

画图:
<OBJECT
id=S
style="LEFT: 0px; WIDTH: 392px; TOP: 0px; HEIGHT: 240px"
height=240
width=392
classid="clsid:369303C2-D7AC-11D0-89D5-00A0C90833E6">
</OBJECT>
<SCRIPT>
S.DrawingSurface.ArcDegrees(0,0,0,30,50,60);
S.DrawingSurface.ArcRadians(30,0,0,30,50,60);
S.DrawingSurface.Line(10,10,100,100);
</SCRIPT>

写注册表:
<SCRIPT>
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");
var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");
</SCRIPT>

 

 

TABLAE相关(客户端动态增加行列)
<HTML>
<SCRIPT LANGUAGE="JScript">
function numberCells() {
    var count=0;
    for (i=0; i < document.all.mytable.rows.length; i++) {
        for (j=0; j < document.all.mytable.rows(i).cells.length; j++) {
            document.all.mytable.rows(i).cells(j).innerText = count;
            count++;
        }
    }
}
</SCRIPT>
<BODY onload="numberCells()">
<TABLE id=mytable border=1>
<TR><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
</TABLE>
</BODY>
</HTML>

 

//打开模式对话框
function doSelectUser(txtId)
{

      strFeatures="dialogWidth=500px;dialogHeight=360px;center=yes;middle=yes ;help=no;status=no;scroll=no";
      var url,strReturn;
 
      url="selUser.aspx";
       
      strReturn=window.showModalDialog(url,'',strFeatures);  

}

 

//返回模式对话框的值
function okbtn_onclick()
{
var commstr='';         
     
window.returnValue=commstr;

      window.close() ;
}


全屏幕打开IE 窗口
var winWidth=screen.availWidth ;
var winHeight=screen.availHeight-20;
window.open("main.aspx","surveyWindow","toolbar=no,width="+ winWidth  +",height="+ winHeight  +",top=0,left=0,scrollbars=yes,resizable=yes,center:yes,statusbars=yes");
break
//脚本中中使用xml
function initialize() {
  var xmlDoc
  var xslDoc

  xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
  xmlDoc.async = false;

  xslDoc = new ActiveXObject('Microsoft.XMLDOM')
  xslDoc.async = false;

 xmlDoc.load("tree.xml")
  xslDoc.load("tree.xsl")
 
 
  folderTree.innerHTML = xmlDoc.documentElement.transformNode(xslDoc)
}

 

 

贴两个关于treeview的 
  <script language="javascript">
<!--
//初始化选中节点
function initchecknode()
{
 var node=TreeView1.getTreeNode("1");
 node.setAttribute("Checked","true");
 setcheck(node,"true");
 FindCheckedFromNode(TreeView1);
}
//oncheck事件
function tree_oncheck(tree)
{
 var node=tree.getTreeNode(tree.clickedNodeIndex);
 var Pchecked=tree.getTreeNode(tree.clickedNodeIndex).getAttribute("checked");
 setcheck(node,Pchecked);
 document.all.checked.value="";
 document.all.unchecked.value="";
 FindCheckedFromNode(TreeView1);
}
//设置子节点选中
function setcheck(node,Pc)
{
 var i;
 var ChildNode=new Array();
 ChildNode=node.getChildren();
 
 if(parseInt(ChildNode.length)==0)
  return;
 else
 {
  for(i=0;i<ChildNode.length;i++)
  {
   var cNode;
   cNode=ChildNode[i];
   if(parseInt(cNode.getChildren().length)!=0)
    setcheck(cNode,Pc);
   cNode.setAttribute("Checked",Pc);
  }
 }
}
//获取所有节点状态
function FindCheckedFromNode(node) {
 var i = 0;
 var nodes = new Array();
 nodes = node.getChildren();
 
 for (i = 0; i < nodes.length; i++) {
  var cNode;
  cNode=nodes[i];
  if (cNode.getAttribute("Checked"))
   AddChecked(cNode);
  else
      AddUnChecked(cNode);
 
  if (parseInt(cNode.getChildren().length) != 0 ) {
   FindCheckedFromNode(cNode);
  }
 }
}
//添加选中节点
function AddChecked(node) {
 document.all.checked.value += node.getAttribute("NodeData");
 document.all.checked.value += ',';
}
//添加未选中节点
function AddUnChecked(node) {
 document.all.unchecked.value += node.getAttribute("NodeData");
 document.all.unchecked.value += ',';
}
//-->
  </script>

 

/********************
函数名称:IsNumber
函数功能:检测字符串是否全为数字
函数参数:str,需要检测的字符串
********************/
function IsNumber(str)
{
var number_chars = "1234567890";
var i;
for (i=0;i<str.length;i++)
{
if (number_chars.indexOf(str.charAt(i))==-1) return false;
}
return true;
}

/********************
函数名称:Trim
函数功能:去除字符串两边的空格
函数参数:str,需要处理的字符串
********************/
function Trim(str)
{
return str.replace(/(^\s*)|(\s*$)/g, "");
}

/********************
函数名称:LTrim
函数功能:去除左边的空格
函数参数:str,需要处理的字符串
********************/
function LTrim(str)
{
return str.replace(/(^\s*)/g, "");
}

/********************
函数名称:RTrim
函数功能:去除右边的空格
函数参数:str,需要处理的字符串
********************/
function RTrim(str)
{
 return this.replace(/(\s*$)/g, "");
}

/********************
函数名称:IsNull
函数功能:判断给定字符串是否为空
函数参数:str,需要处理的字符串
********************/
function IsNull(str)
{
if(Trim(str)=="")
{
return false;
}
else
{
return true;
}
}

 


/********************************************************************
**
*函数功能:判断输入的字符串是否为合法的时间*
*输入参数:输入的字符串*
*返回值:true-合法的时间/false-非法的时间*
*调用函数:*
**
********************************************************************/
function checkDate(strDate)
{
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var strSeparator = "-";
var err = 0;

strDateArray = strDate.split(strSeparator);

if (strDateArray.length != 3)
{
err = 1;
return false;
}
else
{
strYear = strDateArray[0];
strMonth = strDateArray[1];
strDay = strDateArray[2];
}

intday = parseInt(strDay, 10);
if (isNaN(intday))
{
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth))
{
        err = 3;
return false;
}
intYear = parseInt(strYear, 10);
if(strYear.length != 4)
{
return false;
}
if (isNaN(intYear))
{
err = 4;
return false;
}


if (intMonth>12 || intMonth<1)
{
err = 5;
return false;
}

if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
{
err = 6;
return false;
}

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
{
err = 7;
return false;
}

if (intMonth == 2)
{
if (intday < 1)
{
err = 8;
return false;
}

if (LeapYear(intYear) == true)
{
if (intday > 29)
{
err = 9;
return false;
}
}
else
{
if (intday > 28)
{
err = 10;
return false;
}
}
}

return true;
}

 

 


自动显示TXT文本的内容
把如下代码加入<body>区域中
 <script language=vbscript>
Function bytes2BSTR(vIn)
    strReturn = ""
    For i = 1 To LenB(vIn)
        ThisCharCode = AscB(MidB(vIn,i,1))
        If ThisCharCode < &H80 Then
            strReturn = strReturn & Chr(ThisCharCode)
        Else
            NextCharCode = AscB(MidB(vIn,i+1,1))
            strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
            i = i + 1
        End If
    Next
    bytes2BSTR = strReturn
End Function
</script>
<script language="JavaScript">
var xmlUrl = new ActiveXObject('Microsoft.XMLHTTP');
xmlUrl.Open('GET','1.txt');
xmlUrl.Send();
setTimeout('alert(bytes2BSTR(xmlUrl.ResponseBody))',2000);
</script>

 

/********************
函数名称:CookieEnabled
函数功能:判断cookie是否开启
********************/
function CookieEnabled()
{
return (navigator.cookieEnabled)? true : false;
}

/********************
函数名称:PopWindow
函数功能:弹出新窗口
函数参数:pageUrl,新窗口地址;WinWidth,窗口的宽;WinHeight,窗口的高
********************/
function PopWindow(pageUrl,WinWidth,WinHeight)
{
var popwin=window.open(pageUrl,"PopWin","scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width="+WinWidth+",height="+WinHeight);
return false;
}

 


/********************
函数名称:StrLenthByByte
函数功能:计算字符串的字节长度,即英文算一个,中文算两个字节
函数参数:str,为需要计算长度的字符串
********************/
function StrLenthByByte(str)
{
var len;
var i;
len = 0;
for (i=0;i<str.length;i++)
{
if (str.charCodeAt(i)>255) len+=2; else len++;
}
return len;
}

 

 

* JS 中,一些东西不可用的三种展现方式。
我们在WEB项目中,有时候需要在用户点击某个东西的时候,一些东西不可用。如果在客户端实现。最简单的就是利用disabled 。下面罗列的其中三种方式:依次是:不可用(disabled);用一个空白来代替这个地方(Blank);这个区域为空(None)。具体可以查看这个Blog的源文件:
obj.disabled = false;

obj.style.visibility = "hidden";

obj.style.display = "none";


<SCRIPT language=javascript>
function ShowDisableObject(obj)
{
 if(obj.disabled == false)
 {
  obj.disabled = true;
 }
 else{
  obj.disabled = false;
 }
 var coll = obj.all.tags("INPUT");
 if (coll!=null)
 {
  for (var i=0; i<coll.length; i++)
  {
   coll[i].disabled = obj.disabled;
  }
 }
}

function ShowBlankObject(obj)
{
 if(obj.style.visibility == "hidden")
 {
  obj.style.visibility = "visible";
 }
 else
 {
  obj.style.visibility = "hidden";
 }
}

function ShowNoneObject(obj)
{
 if(obj.style.display == "none")
 {
  obj.style.display = "block";
 }
 else
 {
  obj.style.display = "none";
 }
}

</SCRIPT>

 

三個實用的小技巧:關閉輸入法.禁止貼上.禁止複製

 

 

關閉輸入法

本文字框輸入法被關閉: 
語法: style="ime-mode:disabled"
範例:<input type="text" name="textfield" style="ime-mode:disabled">

禁止貼上

本文字框禁止貼上文字: 
語法:onpaste="return false"
範例:<input type="text" name="textfield" onpaste="return false">

禁止複製

本文字框禁止複製: 
語法:oncopy="return false;" oncut="return false;"
範例:<input name="textfield" type="text" value="不能複製裡面的字" oncopy="return false;" oncut="return false;">