本文介绍在JavaScript中向自定义函数传递字符串参数的三种常见方法。第一种是通过this对象传递属性值;第二种是利用HTML标签中省略引号的写法直接传递字符串;第三种则是使用HTML实体或JavaScript转义字符来处理包含双引号的字符串内容。
JavaScript 自定义函数传递字符串参数的三种方式
在JavaScript中,向自定义函数传递字符串参数主要有三种实现方式。第一种方法是通过this对象进行传递;第二种方法是利用HTML标签中省略引号的写法;第三种方法则是使用转义字符,其中在HTML环境中"代表双引号,&apos代表单引号,而在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>