0

在此处输入图像描述我正在做这个项目,我按下一个按钮,将在 textarea 中查找特定单词(可能将光标移动到该特定单词)。我尝试了很多东西,但到目前为止没有运气。这是我想要做的。

$line ="<html>
<head>
<title>Drum studio home</title>
<body>
<img src="/images/fo.png" alt=""/>
</body>
</html> ";

textArea 在 php 页面 test.php

<textarea name="tvalue" id="tvalue">
                              <?php                                  
                                  echo $line . "\r\n";                                                                 
                              ?>
</textarea>
<input type="submit" value="find next" name="submit"/>

当我运行 test.php 时,我会在 textarea 中看到以下内容。

<html>
<head>
<title>Drum studio home</title>
<body>
<img src="/images/fo.png" alt=""/>
<img src="/images/fo.png" alt="fo image"/>
</body>
</html> 

**find next**  --- this is the button

查找下一个按钮将查找没有替代文本的任何图像。我知道我需要 js 或 jquery。我是新来的。所以真的不知道从哪里开始。请帮忙。谢谢

4

1 回答 1

1

解决方案 1:查找下一个空alt属性

JavaScript

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

function nextAlt(input) {
    pos = input.val().indexOf('alt=""');
    if (-1 == pos) {
        alert("None found");
    } else {
        setCaretToPos(input.get(0), pos);
    }
}

HTML

<textarea id="textarea">
    Some sample text.
    <img src="" alt="">
    More text
    <img src="" alt="">
</textarea>
<br>
<a onclick="nextAlt($('#textarea'));">Next</a>

演示

http://jsfiddle.net/rMqbW/

我已经根据这个问题的公认答案构建了这个:

jQuery在文本区域中设置光标位置

解决方案 2:遍历所有 HTML 标记

这是更新的 JavaScript 以跳过所有 HTML 开始标记。我只发布了更新/新的部分。

脚本

// new
(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

// updated
function nextAlt(input) {
    var current = input.getCursorPosition();
    var search = input.val().substr( ( 0 == current ? 0 : current + 1 ) );
    var pos = current + search.search(/<[a-zA-Z]+(>|.*?[^?]>)/) + 1;
    if (-1 == pos) {
        alert("No elements found");
    } else {
        setCaretToPos(input.get(0), pos);
    }
}

演示

http://jsfiddle.net/TmeV3/

这个使用了如何在文本区域中获取光标位置的解决方案?以及来自Create a Javascript RegExp 的正则表达式,用于在 HTML/php 模板中查找开始标签

于 2013-02-17T23:42:41.313 回答