如何测试Javascript实例并相应地创建HTML元素?

时间:2017-07-21 17:56:32

标签: javascript

我知道您可以使用链接到HTML代码的函数激活Javascript,如下所示:

<input type="button" id="foo">
<br>
<script>
    document.getElementById("foo").addEventListener("click", thisFunction);
    thisFunction() {
        blah blah blah
    }
</script>

是否有可能测试一个javascript实例,然后创建一个HTML元素,基本上相反?有点像这样:

<script>
    if (i = 0) {
        create HTML header
    }
</script>

我是JS和HTML的新手,所以如果这是一个简单的回复,请不要发疯。谢谢你的帮助!

完整的JS:

       function myAeroMexicoVacations(cb) {
            aeroMexicoVacationsChecked = cb.checked ? 1 : 0;
            alert(aeroMexicoVacationsChecked + "Aero Mexico Vacations");  
            }
        function myAllInclusiveOutlet(cb) {
            allInclusiveOutletChecked = cb.checked ? 1 : 0;
            alert(allInclusiveOutletChecked + "All Inclusive Outlet");  
            }

        function myBookit(cb) {
            bookitChecked = cb.checked ? 1 : 0;
            alert(bookitChecked + "BookIt");  
            }
        function myCheapCarribean(cb) {
            cheapCarribeanChecked = cb.checked ? 1 : 0;
            alert(cheapCarribeanChecked + "Cheap Carribean");  
            }
        function myCheapTickets(cb) {
            cheapTicketsChecked = cb.checked ? 1 : 0;
            alert(cheapTicketsChecked + "Cheap Tickets");  
            }
        function myDeltaVacations(cb) {
            deltaVacationsChecked = cb.checked ? 1 : 0;
            alert(deltaVacationsChecked + "Delta Vacations");  
            }
        function myExpedia(cb) {
            expediaChecked = cb.checked ? 1 : 0;
            alert(expediaChecked + "Expedia");  
            }
        function myFunJet(cb) {
            funJetChecked = cb.checked ? 1 : 0;
            alert(funJetChecked + "FunJet");  
            }
        function myOrbitz(cb) {
            orbitzChecked = cb.checked ? 1 : 0;
            alert(orbitzChecked + "Orbitz");  
            }
        function myTravelocity(cb) {
            travelocityChecked = cb.checked ? 1 : 0;
            alert(travelocityChecked + "Travelocity");  
        }
        function myUnitedVacations(cb) {
            unitedVacationsChecked = cb.checked ? 1 : 0;
            alert(unitedVacationsChecked + "United Vacations");  
            }
        function myVacationExpress(cb) {
            vacationExpressChecked = cb.checked ? 1 : 0;
            alert(vacationExpressChecked + "Vacation Express");  
            }

        var header = document.createElement('H1');
        var body = document.getElementsByTagName('body');
        body[0].appendChild("Hello");

1 个答案:

答案 0 :(得分:0)

function myFunction() { 
  var header = document.createElement('H1');
  var body = document.getElementsByTagName('BODY');
  var textnode = document.createTextNode('Hello'); 
  header.appendChild(textnode);
  body[0].appendChild(header); 
}

这将告诉您需要了解的内容:https://www.w3schools.com/jsref/dom_obj_all.asp,或者您可以使用MDN网站,这也非常好:https://developer.mozilla.org/en-US/docs/Web/API/Element