DIV CSS 佈局教程網

JavaScript 自訂函式以字串格式傳遞參數的方法
編輯:關於JavaScript     

自訂函式的參數以字串格式傳遞時,主要有三種方式:1、用 this 傳遞;2、引號缺省;3、使用轉義字元(html 中 " 代表雙引號、' 代表單引號,javascript 中則用 \" 等與 Java 通用的轉義字元集)。

<html>
<head>
<script language="LiveScript">
function print(arg){
  alert("你好!" + arg);
}
</script>
</head>
<body>
<form>
<input type="button" name="Button1" value="first" onclick="print(this.str)" str="你好one">
<br><br>
<input type="button" name="button2" value="second" onclick=print("你好two")>
<br><br>
<input type="button" name="button3" value="Third" onclick="print("你好three")">
</form>
</body>
</html>

三種方式各有場景:用 this 搭配自訂屬性傳值,可把資料掛在元素上再傳入;引號缺省時參數直接寫在 onclick 中;而當參數本身需要包含引號時,就得靠 HTML 的 "/' 或 JS 的轉義字元來正確傳遞,避免語法衝突。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved