JavaScript DOM 导航

发布于 2024-11-28 22:07:32 字数 2431 浏览 1 评论 0原文

我正在编写一段代码,允许用户通过页面上的 HTML 元素进行搜索。用户选择他们想要搜索的元素,然后代码遍历每个元素,逐个突出显示它们。如果用户从开始到结束搜索一个元素。但是,如果在一个元素搜索的中间他们将选择切换到另一个元素,则程序可能会因不同原因而开始失败,但主要是因为计数超出范围,例如说我在elementArray[4](其中计数 = 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');
    }
}
} 

Im writing a piece of code which allows the user to search by HTML element on a page..The user selects what element they want to search for, and then the code traverses each element highlighting them one by one..The code works fine if the user searches for one element from start to finish..If however, in the middle of one element search they switch their choice to another element the program can start failing for different reasons but primarily because the count goes out of bound e.g say im on elementArray[4] (where count = 4) for one input element.. then the user switches to table element (which may only have a total of 2 elements in the array) then the index will be out of bounds..

Can someone have a look at the code and perhaps suggest a better way of implementing? I think i should have a seperate function to deal with the scenario when a user switches the element choice in the middle of another element search??

Thanks

    [{
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');
    }
}
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿光 2024-12-05 22:07:32

不知道这是否满足您的所有要求,但这是一个开始

编辑:这是一个演示

// 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

Don't know if this meets all your requirements, but it's a start

Edit: Here's a demo

// 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;
}());

Usage example:

// 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文