Доступ к переменной Javascript в HTML
Скажем, у меня есть следующий JavaScript на странице HTML
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
Как получить значение переменной "splitText" вне тегов script.
Спасибо!
Ответы
Ответ 1
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Ответ 2
Попробуйте следующее:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
Ответ 3
Здесь вы найдете: http://codepen.io/anon/pen/cKflA
Хотя, я должен сказать, что то, что вы просите, это не лучший способ сделать это. Хороший способ: http://codepen.io/anon/pen/jlkvJ
Ответ 4
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
Ответ 5
В необработанном javascript вам нужно поместить идентификатор на свой якорный тег и сделать это:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
<a href = test.html id="someId">I need the value of "splitText" variable here</a>
</body>
</html>