根据对象中的文本获取特定对象

时间:2016-12-06 14:15:04

标签: jquery

我在下面创建了这个功能,它在主体中搜索特定的Word,并且如果它存在与否则能够得到结果。但如果它存在,我如何找到该特定的对象并与之相互作用。

<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>
(function ($) {

    $.fn.WordBreaker = function (x) {

        return this.each(function () {

            var wrapper = $(this);

            var xx = $.extend({
                words: "",
            }, x || {});

            function initialized() {
                xx.words.forEach(function (x, y) {
                    var lw, rw;
                    lw = x.toString().split(",")[0];
                    rw = x.toString().split(",")[1];

                    if ($("body:contains('" + lw + "')").length > 0) {
                       alert("I found an object that contains: " + lw + " , but how do i tager that object?")
                    }

                }, xx.words)
            }
            initialized();
        });
    }

}(jQuery));

var items = [
["THISISALONGTEXTTHATIWANTTOBREAK", "THIS-IS-A-LONG-TEXT-THAT-I-WANT-TO-BREAK"]
];
$('.col-md-5').WordBreaker({ words: items })

1 个答案:

答案 0 :(得分:0)

对于这个答案,我已经从Using jQuery is there a way to find the farthest (deepest, or most nested) child element?获取了代码并将其放在这里。最初的答案来自@Methos。

(function ($) {

    $.fn.WordBreaker = function (x) {

        return this.each(function () {

            var wrapper = $(this);

            var xx = $.extend({
                words: "",
            }, x || {});

            function initialized() {
                xx.words.forEach(function (x, y) {
                    var lw, rw;
                    lw = x.toString().split(",")[0];
                    rw = x.toString().split(",")[1];
                    var all_matched_elements = $(":contains('" + lw + "')");
                    var all_parent_elements = $(all_matched_elements).parents();
                    var all_deepest_matches = $(all_matched_elements).not(all_parent_elements);

                    console.log(all_deepest_matches); // this is an object containing the deepest objects that match the search string

                }, xx.words)
            }
            initialized();
        });
    }

}(jQuery));

var items = [
["THISISALONGTEXTTHATIWANTTOBREAK", "THIS-IS-A-LONG-TEXT-THAT-I-WANT-TO-BREAK"]
];
$('.col-md-5').WordBreaker({ words: items })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
            <div class="col-md-5" style="background: #00ffff">
                <h1>THISISALONGTEXTTHATIWANTTOBREAK</h1>
            </div>
        </div>