简体   繁体   English

JavaScript onclick中传递的参数:this.id与其他属性

[英]Parameter passing in JavaScript onclick: this.id versus other attributes

I suspect there is something basic about JavaScript parameter passing that I do not understand. 我怀疑关于JavaScript参数传递有一些我不了解的基本知识。

If I click on this button, I get an 'undefined' message in the alert box. 如果单击此按钮,则会在警报框中收到“未定义”消息。

<button onclick="play_audio(this.src)" src="foo.m4a">▶</button>

If I click on this button, the string value is passed properly: 如果单击此按钮,则字符串值将正确传递:

<button id="foo.m4a" onclick="play_audio(this.id)">▶</button>

Codepen here: Codepen在这里:

https://codepen.io/anon/pen/JBpMYo https://codepen.io/anon/pen/JBpMYo

A button does not have a src attribute. button没有src属性。 However, you can use this.getAttribute('src') . 但是,您可以使用this.getAttribute('src')

 <button src="foo.m4a" onclick="play_audio(this.getAttribute('src'))" >▶</button> <script> function play_audio(src){ console.log("Playing "+src); } </script> 

It is recommended that you use data-src (you can use any prefix after data- , not necessarily src ) and this.dataset.src instead (you can use the data-* attribute to embed custom data) because it will ensure that your code will not clash with HTML Element attributes for future editions of HTML. 建议您使用data-src (可以在data-之后使用任何前缀,而不必使用src )和this.dataset.src (可以使用data- *属性嵌入自定义数据),因为这将确保您的代码不会与将来的HTML版本的HTML元素属性冲突。 See the documentation . 请参阅文档

 <button data-src="foo.m4a" onclick="play_audio(this.dataset.src)" >▶</button> <script> function play_audio(src){ console.log("Playing "+src); } </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM