简体   繁体   中英

How to call a jQuery function from a for-loop in HTML

so this may be a unique question

I have this XSL for-each loop which generates 3 strings Music, TV, Comedy

The HTML (and my javascript attempt) Uncaught SyntaxError

<div id="rgt" style="position:absolute; height:1px; visibility:hidden;">
    <xsl:for-each select="$GenreTypes/item">
        <div id="rgt-{position()}">
            <xsl:value-of select="sc:fld('title',.)" /><!-- Spits out Music, TV, Comedy -->

            <!-- Where I'm trying to call my function to add titles to an Array -->
            <script type="text/javascript">$.addRelatedGenres('{sc:fld('title',.)}');</script>
         </div>
     </xsl:for-each>
</div>

Basically I'm needing to capture these values into an Array in jQuery. I am 'printing' out the strings I need to a hidden div, as each string is being 'printed' by the for-each loop, I want to call my jQuery function and add each string to the Array.

My jQuery function

function addRelatedGenres(rgt_name) {
    console.log(rgt_name);
}

So far I'm getting syntax errors, not sure how to call a Javascript / jQuery function from the page that isn't an onClick or dependant on the page url (everything happens on 1 page, so there is no new pages, just divs that get unhidden and hidden).

Perhaps there's a better way to do this?

Thanks for taking a peek! :)

Your function is not a "jQuery function" - it's javascript. You need to remove the $. from before the call.

Shouldn't:

<script type="text/javascript">$.addRelatedGenres('{sc:fld('title',.)}');</script>

be

<script type="text/javascript">$.addRelatedGenres('<xsl:value-of select="sc:fld('title',.)" />');</script>

?

IIRR, the { } syntax only works in attributes.

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