如何在 html 中输出 javascript 变量的值

How to output a javascript variable's value inside html?

本文关键字:javascript 变量 输出 html      更新时间:2023-09-26

All,

我有一个返回字符串值的 javascript 例程,我想在我的 html 标签中像这样使用此例程,

<a href="#"><script>getKeyValue('empDesignation')</script></a>

这可能吗?有什么见解吗?

<html>
  <head>
<script type="text/javascript">
function alterText(){
document.getElementById('hello').innerHTML = empDesignation();
}
  function empDesignation(){   
    var output = 'test'
   return output
  }
</script>
  </head>
  <body onload="javascript:alterText()">
    <a id="hello"></a>
  </body>

  </html>

这应该有效。我不得不模拟你的空置指定功能。

document.write(getKeyValue('empDesignation'));这可能会解决问题。

更新:它必须包含在<script>标签中

不,你不能在HTML标签中使用JavaScript变量。您必须使用 DHTML 将值设置为 html。

如果你发布一些代码,我可以帮你

你可以做

var txt = getKeyValue('empDesignation');
$('#result').text(txt);

这假设 getKeyValue() 返回一个字符串。然后你把结果作为元素的文本,id=result

编辑 - 编辑后。 你可以做

.HTML

<a href="#" data-key='empDesignation' class='functional'>your text</a>

.js

//when you click on a link that has the class functional    
$('a.functional').on('click', function(e){
  //prevent the default action
  e.preventDefault();
  //retrieve the data that from the html5 data attribute and pass it to 
  //your custom function
  var result = getKeyValue($(this).data('key'));
  //use the resulting string as the new text for the clicked link
  $(this).text(result);
})

在html标签中,这个getKeyValue('empDesignation')是不可能的,

使用内部 HTML,如下例所示

           <html>
    <script type="text/javascript">
    function changeText(){
        document.getElementById('boldStuff').innerHTML = 'is Software Developer';
    }
    </script>
    <body>
    <p>Employee Designation <b id='boldStuff'>is what?</b> </p> 
    <input type='button' onclick='changeText()' value='Change Text'/>
    </body>
    </html>

编辑

          <script type="text/javascript">
    function changeText(){
             var get_des=getKeyValue('empDesignation');
            document.getElementById('change_id').innerHTML = get_des;
    }
    </script>
           <a href="#" id="change_id" onclick='changeText()'></a>