如何修复.select()无效的问题

时间:2017-02-17 18:06:16

标签: javascript jquery closures hoisting

我正在尝试修改JS脚本来修复搜索关键字的问题,我不确定是什么问题。该脚本仅适用于Internet Explorer,这是一个小问题。

这是一个JS小提琴:https://jsfiddle.net/ettt14k7/5/

此脚本的目的是在使用<telerik:RadGrid />创建的数据网格中查找关键字。在搜索字段中输入所需关键字后,将使用.select()突出显示当前实例(如果有)。

我希望有人可以帮我修改脚本,以便当前实例包含<span class="searchhighlighted"> ... </span>,以便我可以用CSS控制突出显示,以及修复为什么它只适用于IE的问题。我已经尝试过应用以下内容:

instances[currHighlighted].html = '<span class="searchhighlighted">' + instances[currHighlighted].text + '</span>';

但是上面什么也没做。如果我将上述.html更改为使用.text,如下所示:

instances[currHighlighted].text = '<span class="searchhighlighted">' + instances[currHighlighted].text + '</span>';

有效。但是.text以字符串形式输出,并且不会将html标记呈现为标记。

非常感谢任何帮助。感谢

HTML:

<div class="formholder searchkeywordholder">
    <div class="form_inner">
        <div class="formrow form-col-1" tabindex="0">
            <div id="find-in-page">
                <div class="fielditem searchfielditem">
                    <input type="text"
                        id="search-term"
                        placeholder="Type in the phrase to search and click Next..."
                        title="Enter Search Phrase"
                        class="text searchfield"
                        aria-label="Search Keyword Field" />
                    <button id="next"
                        class="button bttn-clear btn-searchnext"
                        title="Next"
                        aria-label="Search Next Button">
                        Next
                    </button>
                    <button id="prev"
                        class="button bttn-find btn-searchprev"
                        title="Previous"
                        aria-label="Search Previous Button">
                        Previous
                    </button>
                </div>
                <label id="labelResult" class="searchInstance"></label>
            </div>
        </div>
    </div>
</div>

    <div class="RadGrid RadGrid_Default mydatagrid staticheaders nostripes" id="ctl00_MainContent_customProjectAssets_gridItems" tabindex="0">
        <div class="rgDataDiv" id="ctl00_MainContent_customProjectAssets_gridItems_GridData">
            <table class="rgMasterTable rgClipCells rgClipCells" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00">

                <tbody>
                    <tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__0">
                        <td valign="middle">
                            <div>

                            </div>
                        </td>
                        <td>
                            <div>
                                <div>
                                    <div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divChildAssetStyle">
                                        Antenna B1
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            Equipment and Materials
                        </td>
                        <td>
                            C2 Equipment
                        </td>
                        <td>
                            Antenna
                        </td>
                        <td>
                            Basic
                        </td>
                        <td>
                            B1
                        </td>
                        <td>
                            <div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divRating" title="Asset's Rate">
                                0.36
                            </div>
                        </td>
                        <td align="center">
                            <span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxOverride" type="checkbox"></span>
                        </td>
                        <td>
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanAssetTag" title="Incident Response/Recovery">IRR</span>
                        </td>
                        <td align="center">
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanClassificationLevel" title="UNCLASSIFIED">U</span>
                        </td>
                        <td align="center">
                            <input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxDelete" onclick="$.onCheckDeleteChange('0');" type="checkbox">
                        </td>
                    </tr>
                    <tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__1">
                        <td valign="middle">
                            <div>

                            </div>
                        </td>
                        <td>
                            <div>
                                <div style="width: 200px; margin: 0 auto;">
                                    <div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divChildAssetStyle">
                                        Content 1
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            This is content
                        </td>
                        <td>
                            My text
                        </td>
                        <td>
                            lorem ipsum dolor
                        </td>
                        <td>
                            sit amet
                        </td>
                        <td></td>
                        <td>
                            <div class="rating_general rating_orange" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divRating" title="Asset's Rate">
                                0.56
                            </div>
                        </td>
                        <td align="center">
                            <span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxOverride" type="checkbox"></span>
                        </td>
                        <td>
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanAssetTag" title="No Asset Tag Assigned"></span>
                        </td>
                        <td align="center">
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanClassificationLevel" title="UNCLASSIFIED">U</span>
                        </td>
                        <td align="center">
                            <input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxDelete" onclick="$.onCheckDeleteChange('1');" type="checkbox">
                        </td>
                    </tr>
                    <tr class="rgRow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__2">
                        <td valign="middle">
                            <div>

                            </div>
                        </td>
                        <td>
                            <div>
                                <div style="width: 200px; margin: 0 auto;">
                                    <div class="iconGridSubordinateArrow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildArrowImage" style="float: left; width: 17px;"></div>
                                    <div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildAssetStyle" style="float: left; width: 180px;">
                                        equivalent
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            People
                        </td>
                        <td>
                            Individuals
                        </td>
                        <td>
                            lorem
                        </td>
                        <td>
                            ipsum
                        </td>
                        <td></td>
                        <td>
                            <div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divRating" title="Asset's Rate">
                                0.44
                            </div>
                        </td>
                        <td align="center">
                            <span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxOverride" type="checkbox"></span>
                        </td>
                        <td>
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanAssetTag" title="No Asset Tag Assigned"></span>
                        </td>
                        <td align="center">
                            <span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanClassificationLevel" title="UNCLASSIFIED">U</span>
                        </td>
                        <td align="center">
                            <input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxDelete" onclick="$.onCheckDeleteChange('2');" type="checkbox">
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

JS:

$(document).ready(function () {
    $(document).on('click', '.btn-searchnext', findNextInstance);
    $(document).on('click', '.btn-searchprev', findPrevInstance);
});

var currHighlighted = null;
var instances = null;
var str = null;
var pageChanged = false;
var isWhiteSpace = false;
var batchEdit = false;

//onkeydown = function (e) {
$(document).on('keydown', '#search-term', function(e) { 

    var search = $('#search-term');
    var active = $(':focus');

    if (e.which == 13) { // ENTER key

        // fpsb-495: check that focus isn't on radconfirm, pager textbox, and make sure the control is visible
        if (
            active.hasClass("rwOkBtn") != -1 &&
            active.hasClass("rwCancelBtn") &&
            active.hasClass("rgPager") == -1 &&

            $('#find-in-page').css('display') != 'none' &&

            !batchEdit
        ) {
            if (str != search.val()) {
                findStrings();
            }
            findNextInstance();
        }
    }
});
//}

// returns true if txtRng is within a DIV tag with a classname "divClass"
function isInDivClass(elt, divClass) {
    elt = elt.parentElement();
    while (elt != null) {

        // the button text shouldn't be picked up by the search control
        if (elt.className == "rgButtonText") {
            return false;
        }

        if (elt.tagName === "DIV" && elt.className.indexOf(divClass) !== -1) {
            return true;
        } else {
            elt = elt.parentElement;
        }
    }
    return false;
}

// finds all instances of string in textfield on page
function findStrings() {

    //str = document.getElementById('search-term').value;
    str = $('#search-term').val();
    isWhiteSpace = str.trim() == "";
    instances = new Array();
    currHighlighted = null;

    if (str && !isWhiteSpace) {
        var strFound = true;

        // used so that the next text range will only look forward on page for string
        var prevTextRange = null;
        while (strFound) {

            // creates a text range obj
            var currTextRange = self.document.body.createTextRange();
            if (prevTextRange != null)
                // starts current range at end point of last range, so no duplicate finds
                currTextRange.setEndPoint("StartToEnd", prevTextRange);
            strFound = currTextRange.findText(str);

            var isInDiv = isInDivClass(currTextRange, "RadGrid RadGrid_Default mydatagrid");
            if (
                strFound &&
                isInDiv &&
                currTextRange.getClientRects().length > 0
            ) {
                instances.push(currTextRange);
            }
            prevTextRange = currTextRange;
        } // end while
    } else { // end if
        instances = null;
        return;
    }

    if (instances.length > 0) {
        // starts at -1 so it will rollover for Prev, start at 1 for Next
        currHighlighted = -1;
    }

    return;
}

// highlights the next word in instances array for the current search term
function findNextInstance() {

    // call findStrings() if page was changed 
    //if (pageChanged || str != document.getElementById('search-term').value) {
    if (pageChanged || str != $('#search-term').val()) {
        findStrings();
        pageChanged = false;
    }

    // if nothing in text field or no instances of string on page
    if (!instances || instances.length === 0 || !str) {
        if (str != null || isWhiteSpace) {
            if (str.length == 0 || isWhiteSpace) {
                radalert("Please enter a phrase to search!", 250, 110);
                $('.searchInstance').text("");
            } else {
                $('.searchInstance').text("No instances found on this page.");
                radalert("Searched string not found on this page!", 250, 110);
            }
            return;
        } else if (str == null) {
            //alert("in find next when str i snull: " + str);
            //radalert("Please enter a word to search!", 250, 110);
            console.log('Field left empty. Nothing to search.');
        }

        $('.searchInstance').text("");

        return;
    }

    // allows Next to "roll over" from last instance to first instance again
    currHighlighted = currHighlighted + 1;
    if (currHighlighted == instances.length || currHighlighted == -1) {
        currHighlighted = 0;
    }

    instances[currHighlighted].select();
    $('.searchInstance').text("Instance " + (currHighlighted + 1) + " of " + instances.length + " found on this page.");

    return false;
}

// highlights the previous word in instances array for the current search term
function findPrevInstance() {

    // call findStrings() if page was changed 
    //if (pageChanged || str != document.getElementById('search-term').value) {
    if (pageChanged || str != $('#search-term').val()) {
        findStrings();
        pageChanged = false;
    }

    // if nothing in text field or no instances of string on page
    if (!instances || instances.length === 0 || !str) {
        if (str != null || isWhiteSpace) {
            if (str.length == 0 || isWhiteSpace) {
                radalert("Please enter a phrase to search!", 250, 110);
                $('.searchInstance').text("");
            } else {
                radalert("Searched string not found on this page!", 250, 110);
                $('.searchInstance').text("No instances found on this page.");
            }
        } else if (str == null) {
            radalert("Please enter a phrase to search!", 250, 110);
        }
        return;
    }

    // allows Prev to "roll over" from first instance to last instance
    if (--currHighlighted < 0)
        currHighlighted = instances.length - 1;

    instances[currHighlighted].select();

    $('.searchInstance').text("Instance " + (currHighlighted + 1) + " of " + instances.length + " found on this page.");

    return false;
}

function shouldRefresh() {
    // next time Next or Prev is clicked, call findStrings again since grid state is changed
    pageChanged = true;
    //var searchTerm = document.getElementById('search-term').value;
    var searchTerm = $('#search-term').val();
    if (searchTerm != null && searchTerm !== '') {
        $('.searchInstance').text("Page changed, press Next or Previous to refresh search!");
    }
}

function clearSearchField() {
    //document.getElementById('search-term').value = "";
    $('#search-term').val("");
    $('.searchInstance').text("");
    instances = null;
    isWhiteSpace = false;
}

function ToggleSearchDiv(status) {
    // document.getElementById('find-in-page').style.display = status;
    if (status == 'none') {
        document.getElementsByClassName('searchkeywordholder')[0].style.display = 'none';
    } else {
        // We want to avoid using display: inline
        document.getElementsByClassName('searchkeywordholder')[0].style.display = 'block';
    }
}

function ToggleBatchEdit(status) {
    batchEdit = status;
}
// END of find in page

0 个答案:

没有答案