简体   繁体   中英

How to use a JavaScript variable as a XHTML attributes value?

I have tried:

<!--...-->
<script type="text/javascript">
  var myVar = "some string";
</script>
<!--...-->
<input name="&{myVar};" ... />
<!--...-->

But using FireFox, the name is set to the literal string: "&{myVar};" instead of the value of myVar...

UDPATE: I see this called JavaScript Entities and hasn't been supported for a long time - but there must be way if one can include JavaScript directly in events (I realize attributes are not events, so JavaScript probably isn't evaluated).. ?! It would be a lot nicer than hardcoding the value as it used elsewehere a lot..

var myInput = document.createElement('input');
myInput.setAttribute('name', myVar);

someContainElement.appendChild(myInput);

I'm afraid you have to use Javascript to manipulate the html element. You can use jQuery to make this easier:

<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<input id="myInput" .../>
<script>
    var myVar = "value";
    $("#myInput").attr("name", myVar);
</script>

Both Phil's and Xenoflex's ways, are the better way to go. They are actually doing the same thing just different ways, one using jQuery the other pure Javascript.

Alex's will work as well but then everything is hardcoded and somewhat less flexiable to future changes. The way Alex left his answer open you could print the string or assign it to a variable to be appended to a javascript object.

I think the nearest match to what you're looking for is:

<script type="text/javascript">
  var myVar = "some string";
</script>
...
<script type="text/javascript">
  document.write('<input name="' + myVar + '" ... />')
</script>

But as I said you should really take one of the first two approaches.

Here's what you need to do.

Start by never reading javascript tutorials from a Java site again. Different monsters entirely, plus the tutorials on the site you're referencing are horrible.

Second, get a copy of Javascript the Good Parts, http://www.amazon.com/dp/0596517742/ This book is perhaps the most useful book ever written (in my opinion) about the language itself. It doesn't say anything about dealing with DOM API's.

I encourage you to learn the language itself before getting too deep into javascript libraries like jQuery. It'll do you a load of good sooner rather than later.

Once you're at least somewhat familiar with the proper ways to use javascript as a language, start investing your time into one library or another. jQuery is probably the most used, well loved, and kindest library out there. It will make dealing with cross-browser crap SO much easier for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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