js动态添加html标签函数中的参数写法

js动态添加html标签,此html中包含onclick等事件,必然要引用函数,那么函数中的参数如何写?

1,function showi(m){
alert(m);
}
function change(){
var  x=6;
document.write('<a href="#"  onclick="showi(\'  '+x+'   \')">点击</a>');
};
change();

//6

2,document.write('<a href="#"  onclick="showi( '+x+'  )">点击</a>');

//6

3,document.write('<a href="#"  onclick="showi(  x  )">点击</a>');

//出错

4,document.write('<a href="#"  onclick=" x=7; showi(\'  '+x+'   \')">点击</a>');

//6

5,document.write('<a href="#"  onclick=" x=7; showi(   '+x+'   )">点击</a>');

//6

6,document.write('<a href="#"  onclick=" x=7; showi(   x   )">点击</a>');

//7

7,document.write('<a href="#"  onclick=" x=\'hello\'; showi(   x   )">点击</a>');

//hello

8,var  x="HELLO";

document.write('<a href="#"  onclick="  showi(\' '+   x +' \'   )">点击</a>');

//HELLO;

9, var x=6;

document.write('<a href="#"  onclick="  showi(\' +   x + \'   )">点击</a>');

//+x+

10,var x=6

document.write('<a href="#"  onclick="  showi('+   x +'    )">点击</a>');

// 6

根据以上实验:

在js动态添加html标签,此html中包含onclick等事件,引用函数,那么函数中的参数这样写:

当函数中的参数来自于标签中的变量,参数形式就是普通的形式,直接showi(  x  )就行了。

eg:document.write('<a href="#"  onclick=" x=\'hello\'; showi(   x   )">点击</a>');

document.write('<a href="#"  onclick="  showi(   'hello'   )">点击</a>');

document.write('<a href="#"  onclick="  showi(  7  )  ">点击</a>');

当函数中的参数来自于动态加载html的js,若参数是数字,则showi( '+x+');若参数是字符串,则showi(\'  '+x' \');

猜你喜欢

转载自blog.csdn.net/kalinux/article/details/81745615