Javascript DOM навигация - PullRequest
       12

Javascript DOM навигация

0 голосов
/ 10 августа 2011

Я пишу фрагмент кода, который позволяет пользователю осуществлять поиск по элементу HTML на странице. Пользователь выбирает, какой элемент он хочет найти, а затем код пересекает каждый элемент, выделяя их один за другим. Код работает нормально, если пользователь ищет один элемент от начала до конца ... Однако, если в середине поиска одного элемента они переключают свой выбор на другой элемент, программа может начать сбой по разным причинам, но в первую очередь потому, что счетчик выходит за пределы скажем im для elementArray [4] (где count = 4) для одного входного элемента ... затем пользователь переключается на элемент таблицы (который может иметь всего 2 элемента в массиве), тогда индекс будет вне границ ..

Может кто-нибудь взглянуть на код и, возможно, предложить лучший способ реализации? Я думаю, что у меня должна быть отдельная функция, чтобы иметь дело со сценарием, когда пользователь переключает выбор элемента в середине поиска другого элемента ??

Спасибо

    [{
type: 'select',
id: 'findNext',
label: 'Find next :',
isChanged: false,
labelLayout: 'horizontal',
accessKey: 'R',
items: [
    ['Form', 'form'],
    ['Input', 'input'], // Checkbox, radio, textfield, button, image
    ['Table', 'table'],
    ['Textarea', 'textarea'],
    ['Select', 'select'],
    ['Anchor', 'a'], // [option, ]
    ['Image', 'img']
],
}, {
type: 'button',
align: 'left',
style: 'width:100%',
label: 'Find Next',
id: 'findX', 
onClick: function () {
var dialog = this.getDialog();

if (typeof currentElement != 'undefined') {
    x = currentElement;
    x.removeAttribute('style'); // Remove the highlight from the current element
}

if (count != null) {
    count++;
} else {
    count = 0;
}

if (selectOptionArray == null) {
    selectOptionArray = new Array();
}

var selectOption = dialog.getValueOf('find', 'findNext'); // Get user selection e.g input, table etc
elementArray = documentNode.getElementsByTagName(selectOption);

currentElement = elementArray[count]; // Keep a reference of the current choice so the higlight can be removed on line 7
getSelection();

function getSelection() {
    if (count > 0) { // Check if there are two elements to compare
        areElementsSame();
    }

    if ((elementArray.length > 0) && (count < elementArray.length)) { // Is count out of bounds?
        nextElement(count, elementArray);

    } else {
        alert("Search complete..No elements exist.");
        count = null;
    }
}

function areElementsSame() {
    if (count >= elementArray.length) {
        count = 0;
        nextElement(count, elementArray);
    } else if (elementArray[count].nodeName == x.nodeName) {
        nextElement(count, elementArray);
    } else {
        count = 0;
        nextElement(count, elementArray);
    }
}

function nextElement() {
    if (count < elementArray.length) {
        elementArray[count].setAttribute('style', 'background-color: blue');
        elementArray[count].scrollIntoView(true);
    } else {
        alert('count is > elementArray.length, all elements navigated');
    }
}
} 

1 Ответ

0 голосов
/ 10 августа 2011

Не знаю, соответствует ли это всем вашим требованиям, но это начало

Редактировать: Вот демоверсия

// call search() repeatedly to get found elements
// call it at least once with the tag name you're searching
// for - after that you can just call search() with no argument.
// If search() returns null, no element were found
// search.results() will return an array of found elements
// search.currentIndex() will return the current index
var search = (function(){
  var foundElements = [],
      lastTagName,
      currentIndex = -1;

  function next() {
    if( foundElements.length === 0 ) {
      return null;
    }
    currentIndex = (currentIndex + 1) % foundElements.length;
    return foundElements[currentIndex];
  }

  function search(tagName) {
    if( tagName && tagName !== lastTagName ) {
      foundElements = document.getElementsByTagName(tagName);
      lastTagName   = tagName;
      currentIndex  = -1;
    }
    return next();
  }

  search.results = function() {
    return foundElements.slice();
  };

  search.currentIndex = function() {
    return currentIndex;
  };

  search.clear = function() {
    foundElements = [];
    lastTagName = null;
    currentIndex = -1;
  };

  return search;
}());

Пример использования:

// first time you search for a specific tag name,
// you get the first matching element back. 
result = search('div'); // find first div element

// If you search for that same tag name again,
// you'll get the next matching element
result = search('div'); // get the 2nd div element
result = search('div'); // get the 3rd div element

// you can also omit the tag name, if you just mean
// "give me the next result"
result = search(); // get the 4th div element

// if you pass a different tag name, it'll start a
// new search
result = search('form'); // get the 1st form
result = search('form'); // get the 2nd form
result = search('form'); // get the 3rd form
// etc...

// if you want to explicitly start a new search
// call search.clear()
result = search('form'); // get the 4th form
result = search.clear(); // clear the search
result = search('form'); // get the 1st form
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...