简体   繁体   English

您将如何直接在html中引用javascript函数?

[英]How would you refer to javascript function directly in html?

So the idea is this. 因此,想法就是这样。 I have an array in the js file as well as a function that refers to a random element from that array. 我在js文件中有一个数组,还有一个引用该数组中随机元素的函数。 I want to be able to click a button and the text in the span changes to a random element in the array. 我希望能够单击一个按钮,并且范围内的文本更改为数组中的随机元素。 I already have a way of doing this. 我已经有办法做到这一点。 I have a span with an id of "change_equivalently". 我的ID为“ change_equivalently”。 Then in the javascript file, I have 然后在javascript文件中

var Equivalentlys = [
"Equivalently, ",
"Alternatively, ",
"Another way of saying this is that "
];

$('#shuffle').click(function() {
    var length = (Equivalentlys.length + 1);

    var x = Math.floor(Math.random()*length);

function Equivalently(i){
    return Equivalentlys[i];
};

$('#change_equivalently').text(Equivalently(x));

});

My question is that when I write out the html code, I always have to write 我的问题是当我写出html代码时,我总是不得不写

<span id = "change_equivalently"> ... </span>

in order to be able to change the words up upon clicking the button. 为了能够在单击按钮时更改单词。

But I want an easier way. 但是我想要一个更简单的方法。 I tried something like 我尝试了类似的东西

  <var> Equivalently( 1 ) </var> 

to see if I could refer to the javascript function, but it didn't work. 看看我是否可以引用javascript函数,但是没有用。

How could I go about approaching this? 我该如何解决?

First of all, the approach you're currently using is better than what you want--it separates presentation from function and is widely regarded as the best practice. 首先,您当前使用的方法比您想要的要好 -将表示与功能分开,被广泛认为是最佳实践。

However, you can (but, as I said, probably shouldn't ) include code to be called when your element is clicked: 但是,您可以 (但是,正如我所说,可能不应该 )包含单击元素时要调用的代码:

<span onclick="doStuff()"> blarg </span>

If you just want to be able to have JavaScript code that turns into HTML (like PHP or similar templating systems), you won't be able to do it with JavaScript. 如果您只希望能够将JavaScript代码转换为HTML(例如PHP或类似的模板系统),则无法使用JavaScript来实现。

Ultimately, the best way is just to use a span to mark the content and add a click event in your script, the way you're doing right now. 最终,最好的方法就是使用跨度标记内容并在脚本中添加click事件,这就是您现在正在做的方式。 This is the best semantically: in the html, all you say is that that particular word/position is changeable; 这在语义上是最好的:在html中,您所说的只是该特定单词/位置是可变的; you specify how it changes in your code. 您指定它在你的代码如何变化。

Do you mean this? 你是这个意思吗

<script type="text/javascript">
  Equivalently(1)
</script>

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

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