简体   繁体   中英

Scroll to elements from two different lists in the same document that have the same id value

In the following case there are two lists, one being nested within the other.

<q-list>
    <q-item
        v-for="item in data"
        :key="item.id_data"
        :id="item.id_data"
        >
        <q-item-section>
            <div>
                <span {{ item.name }} </span>

                <q-item
                    v-for="stuff in item"
                    :key="stuff.id_stuff"
                    :id="stuff.id_stuff">
                    <q-item-section>
                        <span"> {{ stuff.name }} </span>
                    </q-item-section>
                </q-item>

            </div>
        </q-item-section>
    </q-item>
</q-list>

Two click events can be triggered that generated a scroll to a element of the lists:

1- In the first case, the scroll must be done for the element to which the id corresponds to item.id_data

2- In the second case, the scroll must be done for the element to which the id corresponds to stuff.id_stuff

This means that the data id value can match the stuff id value (ie, item.id_data = 4 , stuff.id_stuff = 4 ).

This causes problems when using document.getElementById(id).

Example of the scrollTo function:

scrollTo (id) {
    const ele = document.getElementById(id)
    const target = getScrollTarget(ele)
    const offset = ele.offsetTop - ele.scrollHeight    
    const duration = 500
    setScrollPosition(target, offset, duration)
},

how to solve this?

You could bind a prefix to each ID to differentiate them:

<q-list>
    <q-item
        v-for="item in data"
        :key="item.id_data"
               👇
        :id="'data_' + item.id_data"
        >
        <q-item-section>
            <div>
                <span {{ item.name }} </span>

                <q-item
                    v-for="stuff in item"
                    :key="stuff.id_stuff"
                            👇
                    :id="'stuff_' + stuff.id_stuff">
                    <q-item-section>
                        <span"> {{ stuff.name }} </span>
                    </q-item-section>
                </q-item>

            </div>
        </q-item-section>
    </q-item>
</q-list>

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