简体   繁体   中英

Select cell in html table generated by foreach

please help me with knockout.js code

I try select element in table by id and change it's css style, but all rows have same id and I can't using function getElementById. How I can do this simple thing ?

<tbody data-bind="foreach: times">
        <tr>
            <td id=$index() data-bind="click: $root.select.bind($data, $index(), 0)> </td>

        ....

        <td id=$index() data-bind="click: $root.select.bind($data, $index(), 19)> </td>

    <tr>
</tbody>

Id's should always be unique. Assign the same class to all elements you're interested in and use a bit of jquery:

document.getElementsByClassName('class_name')

EDIT: Good point. I was originally going to suggest using jquery and then remembered this function. If you are using jquery library, you can also try this:

$('.class_name').each(function(index) {
    ...do something...
});

EDIT: to answer your question, there are a few ways to do this:

$('.class_name').attr('id', new_id)

or

$('.class_name').addClass('class_name')

depending on what exactly you're trying to do

Try to use such code:

<tbody data-bind="foreach: times">
    <tr>
        <td data-bind="attr: {id: $index()}, click: $root.select.bind($data, $index(), 0)></td>
    <tr>
</tbody>

Read more about attr binding here: http://knockoutjs.com/documentation/attr-binding.html

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