在javascript中,您可以使用多种方法将字符串传递给函数。但哪一个是最正确的方式?
eg 1 <a onclick='myfunction("mystring")'>1</a>
eg 2 <a onclick="myfunction('mystring')">1</a>
修改
我不认为这是一个重复的问题,值得一个downvote。那个问题是在javascript中处理code
。这是关于从html到代码的调用。
答案 0 :(得分:2)
两者都是完全可以接受的变体,只是与您用于最外层引用的内容保持一致。我更喜欢JS中的单引号。
答案 1 :(得分:2)
旧的方式是
<a onclick="myfunction('mystring')">1</a>
但这有很多限制。
我认为将字符串(变量)传递给javascript的最正确方法是:
与clickevents交互的新方法是在javascript代码中添加eventlisteners。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function(){
var handler=function(e){//define your function (click handler)
console.log(e,this);// contains the event details and the clicked element details
}
var a=document.getElementsByTagName('a')[0]; // with this line i get the first a
a.addEventListener('click',handler,false);// add the click lisstener
}
</script>
</head>
<body>
<a>1</a>
</body>
</html>
所以现在你只需找出在<a>1</a>
<a title="mystring">1</a>
要在您的处理程序中获取此信息,您只需编写this.title
即可获取字符串
在锚内
<a>mystring</a>
要在您的处理程序中获取此信息,您只需编写this.innerText
即可获取字符串
还有一种新方法可以在名为dataset
的元素中存储信息<a data-string="mystring">1</a>
要在您的处理程序中获取此信息,您只需编写this.dataset['mystring']
即可获取字符串
最常见的方式是目标:
e.target.title
e.target.innerText
e.target.dataset['string'];
使用此addEventListeners可以添加多个点击事件......或者在另一侧,它允许您只需点击一下即可处理多个元素。
答案 2 :(得分:1)
两者基本相同。编码内联属性时,我更喜欢使用第二个版本,因为对属性使用双引号更常见:
<img src="path/to/image">
在纯粹的Javascript代码中,不在内联HTML单字符串和双字符串完全等效(不同于PHP或Perl,其中双引号进行插值),所以只选择一个约定。我更喜欢默认使用单引号并使用双引号来表示向用户公开的字符串(将来可能需要翻译这些字符串,依此类推)