#1
  1. a lazy guy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2001
    Location
    Hong Kong
    Posts
    99
    Rep Power
    13

    JavaScript question.


    <a id="abc" href="#">hello world</a>


    in the above html, i can use
    'abc.innerText' to retreive the text inside <a id="abc">


    ==========================================
    <a id="abc" href="#" onclick="open('abc')">hello world</a>

    function open(id)
    {
    var mystr = id;
    alert(mystr.innerText);
    }

    in the above codes, it is not working. I know i cannot make a 'string' as a 'object'.
    anyone got a solution here?
  2. #2
  3. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2001
    Location
    England
    Posts
    24
    Rep Power
    0
    Oh dear, this one took me longer than it should have...

    Code:
    function aopen(id)
    {
        alert(document.getElementById(id).innerText);
    }
    Code:
    <a id="abc" href="#" onclick="aopen('abc')">hello world</a>
    It was mainly because open() is already taken (as in window.open(), window being the default object in a page) so that name wouldn't work. I also took the liberty of changing it to be slightly more DOM correct.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2001
    Posts
    765
    Rep Power
    13
    <a id="abc" href="#" onclick="show('abc');return false;">hello world</a>

    function show(id)
    {
    var mystr = id;
    alert(window[mystr].innerText);
    alert(eval(mystr).innerText);
    }

    It worked originally in Internet Explorer because only Internet Explorer turns element ids into global variables (window properties). You can use a string as a legitimate variable name by 1)eval()ing it or 2)using it as an array index ("associative" array) of the appropriate object - in this case, the window. Of course, there has to be a variable of that name already defined, or you'll get an error.

    open() is both a method of the window and the document, not the best choice for a variable name.

    http://www.xs4all.nl/~ppk/js/associative.html
    Last edited by mrrichardfeder; December 12th, 2001 at 01:43 PM.

IMN logo majestic logo threadwatch logo seochat tools logo