JS - 带标签的getElementById

时间:2017-02-02 15:49:11

标签: javascript html getelementbyid

我试图改变一些元素,但onclick标签丢失了。如何获取包含标签的元素?

var first = document.getElementById("demo1").innerHTML; // I want to keep the onclick tag for this one.

如果你需要,这是代码的其余部分

HTML文件:

<p id="demo"> Start </p>

<p id="demo1" onclick="alert('hello')"> First </p>
<p id="demo2"> Second </p>
<p id="demo3"> Third </p>

<script type="text/javascript" src="temp.js"> </script>

<script> 
    var first = document.getElementById("demo1").innerHTML;
    var second = document.getElementById("demo2").innerHTML;
    var third = document.getElementById("demo3").innerHTML;
    shuffleOptions(first, second, third); 
</script>

temp.js文件:

function shuffleOptions(first, second, third) {
    var options = [first, second, third];
    options.sort(function(a, b){return 0.5 - Math.random(); });
    document.getElementById("demo").innerHTML = options;
}

1 个答案:

答案 0 :(得分:1)

试试这个

function shuffleOptions(first, second, third) {
var options = [first, second, third].sort(function() {
return .5 - Math.random();
});
document.getElementById("demo").innerHTML = options;
}