如何通过textnode或文本内容获取对应span?表单空值时如何删除对应span?
实现方案
你原来的函数只传入字段值无法关联到对应的span元素,首先需要给函数新增字段名参数,关联对应DOM元素,以下是两种实现方式:
方案1:通过class属性匹配(更推荐,性能高、稳定性强)
你的span元素的class刚好和表单字段名完全对应,直接用class选择器匹配是最优解:
// 新增fieldName参数,对应表单字段名/span的class名 function insertMe(fieldValue, fieldName) { // 匹配对应class的span元素,加可选链避免元素不存在时报错 const targetSpan = document.querySelector(`span.${fieldName}`) // 加trim过滤全空格的无效输入 if (fieldValue.trim() === "") { targetSpan?.remove() return '' } else { // 非空直接给span赋值 targetSpan.textContent = fieldValue return fieldValue } } // 调用示例 const title = document.getElementsByName('title')[0].value const author = document.getElementsByName('author')[0].value const isbn = document.getElementsByName('isbn')[0].value insertMe(title, 'title') insertMe(author, 'author') insertMe(isbn, 'isbn')
方案2:通过文本内容匹配(满足你要求的textnode匹配需求)
如果一定要通过span内的占位文本匹配,可以遍历span匹配占位内容,缺点是依赖占位文本不能修改,稳定性差:
// 封装匹配占位文本的方法 function getSpanByPlaceholder(fieldName) { const allSpans = document.querySelectorAll('span') const placeholder = `// the value of ${fieldName}` for (const span of allSpans) { if (span.textContent.trim() === placeholder) { return span } } return null } function insertMe(fieldValue, fieldName) { const targetSpan = getSpanByPlaceholder(fieldName) if (fieldValue.trim() === "") { targetSpan?.remove() return '' } else { targetSpan.textContent = fieldValue return fieldValue } }
内容的提问来源于stack exchange,提问作者Papis Sahine
相关产品推荐
相关产品推荐

