Skip to content

findOne

查找元素功能(选择器),只获取一个元素。

想获取一个数组,请使用 find()

关键方法

findOne ( condition: number | string | IFindMethod ): UI

通过 idinnerIdclassNametag、函数等条件查找元素,只返回一个元素。

findId ( id: number | string ): UI

查找 id, 支持查找数字类型的 id(必须原始 id 类型为数字)。

归属

UI

示例

通过 id 查找

ts
import { Leafer, Rect } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect1 = new Rect({ id: 'block', fill: '#32cd79' })
const rect2 = new Rect({ fill: '#32cd79' })

leafer.add(rect1)
leafer.add(rect2)

console.log(
    leafer.findOne('#block') // rect1
)

通过 innerId 查找

ts
import { Leafer, Rect } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect1 = new Rect({ id: 'block', fill: '#32cd79' })
const rect2 = new Rect({ fill: '#32cd79' })

leafer.add(rect1)
leafer.add(rect2)
console.log(
    leafer.findOne(rect2.innerId)  // rect2
)

通过 className 查找

ts
import { Leafer, Rect } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect1 = new Rect({ className: 'menu', fill: '#32cd79' })
const rect2 = new Rect({ className: 'menu', fill: '#32cd79', x: 150 })
const rect3 = new Rect({ fill: '#32cd79', x: 300 })

leafer.add(rect1)
leafer.add(rect2)
leafer.add(rect3)

console.log(
    leafer.findOne('.menu') // rect1
)

通过 tag 查找

ts
import { Leafer, Rect, Ellipse } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect1 = new Rect({ fill: '#32cd79' })
const rect2 = new Rect({ fill: '#32cd79', x: 150 })
const ellipse = new Ellipse({ fill: '#32cd79', x: 300 })

leafer.add(rect1)
leafer.add(rect2)
leafer.add(ellipse)

console.log(
    leafer.findOne('Rect')  // rect1
)

通过 函数 查找

ts
import { Leafer, Rect, Ellipse } from 'leafer-ui'

const leafer = new Leafer({ view: window })

const rect1 = new Rect({ fill: '#32cd79', stroke: 'black' })
const rect2 = new Rect({ fill: '#32cd79', x: 150 })
const ellipse = new Ellipse({ fill: '#32cd79', stroke: 'black', x: 300 })

leafer.add(rect1)
leafer.add(rect2)
leafer.add(ellipse)

console.log(
    leafer.findOne(function (item) {
        return item.stroke === 'black' ? 1 : 0 // rect1
    })
)

Released under the MIT License.