jQuery选择元素中的匹配文本

时间:2017-07-07 18:35:24

标签: javascript jquery html html5

我需要一种方法将元素id和字符串传递给一个函数,该函数选择元素文本中任何出现的字符串,该字符串尚未包含在子元素中。

我有一个现有的事件处理程序,当用户突出显示一段文本时,它会执行一些操作,包括将文本包装在元素中。但是,某些字符串可以自动匹配而无需用户选择,这正是我在这里要完成的。一个不同的事件有时会生成一个元素id和一个字符串,并且元素文本中所有未准备好标记的字符串的所有实例都应该传递给事件处理程序,就像用户选择它们一样。

示例:

var selectionString = 'word';
<p id="1">select this word, but not this <span>word</span>, but yes to this word.</p>

// My approach so far which may not be on the right track.
function selectStringInElement(selectionString, elementId){
    var el = document.getElementById(elementId);
    var selections = el.innerHTML.split(/<.+>/);
    for(var i=0; i < selections.length; i++){
        // if the selection contains the selectionString, find its range, select it, and pass to existing handler.
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

HTML节点可以通过node.childNodes访问子节点,您可以通过node.nodeType判断子节点是文本还是元素。

此示例将搜索字符串和元素ID进行搜索,对其进行过滤,以便仅保留文本节点,然后执行替换以生成新的html字符串。您不能将HTML字符串插入文本节点,因此我使用临时div将html字符串解析为节点,然后在删除源文本节点本身之前将其注入元素的父节点。

&#13;
&#13;
.conf
&#13;
function selectStringInElement(selectionString, elementId, className) {
  $("#" + elementId).contents()
  .filter(function(i, el){ 
    // only process text nodes
    return el.nodeType == 3 
  }).each(function(i, el){
    // create a div to process our html string with new tags
    var fake = document.createElement('div');

    fake.innerHTML = el.textContent.replace(
      new RegExp(selectionString,'g'),
      "<span class='" + className + "'>" + selectionString + "</span>"
    );

    // take all the nodes in our div and append them to the actual element's parent
    $(fake.childNodes).each(function(i, child) {
      el.parentNode.insertBefore(child, el);
    });

    // we've now duplicated our actual element with a number of new elements, we don't need to keep the original
    el.parentNode.removeChild(el);
  });
}
selectStringInElement('chowder','test', 'red');
selectStringInElement('ukulele','test', 'blue');
&#13;
.red {
  color: #f00;
}
.blue {
  color: #00f;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是JQuery实现:

JSFiddle

// presentational component
class Signup extends Component {
    render() {
        const { handleSubmit } = this.props;
        return (
            <div>
                <h1>Signup</h1>
                <form onSubmit={handleSubmit}>
                    <div>   
                        <label>
                            Email: 
                            <Field component="input" type="email" name="email" />
                        </label>
                    </div>
                    <div>   
                        <label>
                            Password: 
                            <Field component="input" type="password" name="password" />
                        </label>
                    </div>
                    <button type="submit" >Submit</button>
                </form>
            </div>
        )
    }
}

export default reduxForm({
    form: 'Signup',
    enableReinitialize: true
})(Signup)

// redux container component
const mapDispatchToProps = (dispatch) => {
    return {
        handleSubmit: (values) => {
            console.log(values.email); // outputs undefined!
        }
    };
}

const SignupContainer = connect(
    null,
    mapDispatchToProps
)(Signup)

export default SignupContainer;


// reducer index.js
import { reducer as formReducer } from 'redux-form';

export const appReducer = combineReducers({
    form: formReducer
})


// store.js
export const store = createStore(
    appReducer,
    applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
    )
);

结果:“word”被span标记包围,而onMouseOver事件附加到该标记。

HTML结果代码:

packagingOptions {

   exclude 'META-INF/DEPENDENCIES.txt'
   exclude 'META-INF/LICENSE.txt'
   exclude 'META-INF/NOTICE.txt'
   exclude 'META-INF/NOTICE'
   exclude 'META-INF/LICENSE'
   exclude 'META-INF/DEPENDENCIES'
   exclude 'META-INF/notice.txt'
   exclude 'META-INF/license.txt'
   exclude 'META-INF/dependencies.txt'
   exclude 'META-INF/LGPL2.1'

   }