评估未关注的元素

时间:2018-02-04 14:38:08

标签: javascript jquery

我需要评估隐藏input字段的内容,其值的变化取决于无序列表的内容。作为参考,此input字段是Tag-it!单输入字段(2)程序集的一部分。

评估此类字段的问题是onchange似乎没有触发input元素,因为该元素不在焦点上。这意味着我有两个可能的方向:

  • 弄清楚当元素不在焦点时如何激活onchange事件;
  • 评估无序列表的内容。

这些选项中的后一种似乎是最合适的,但它也可能很重且可能不准确。我应该选择哪种方法?

HTML:

<div id="Likes">
  <div class="form-modal-back">
    <div class="form-modal-title">
      <h4>Choose some things you like</h4>
    </div>
    <div class="form-modal-main">
      <h5>Start by typing a few letters, and choose from the suggestions</h5>
      <div class="gap20"></div>
      <div class="tagBox">
        <input id="likesTags" name="tags" />
      </div>
      ...
      <a href="#Dislikes">
        <input class="form-modal-button-right hiddenLink" id="onb5" type="button" value="Next" />
      </a>
      ...
运行时

HTML:

<input id="likesTags" name="tags" class="tagit-hidden-field">
<ul class="tagit ui-widget ui-widget-content ui-corner-all">
  <li class="tagit-new">
    <input class="ui-widget-content ui-autocomplete-input" autocomplete="off" type="text">
    <span role="status" aria-live="polite" class="ui-helper-hidden-accessible">1 result is available, use up and down arrow keys to navigate.</span>
  </li>
</ul>

JS:

$("#likesTags").onchange(function () {
    var text = $("#likesTags").val();
    if (text.length > 2)
    {
        pageCompletionSequence += "1";
        checkCompletion("#onb5", "#Dislikes", "11");
    }
    else 
    {
        pageCompletionSequence = "1";
        elementRestore("#onb5");
    }
})

function checkCompletion(id, np, seq) {
    if (pageCompletionSequence == seq) {
        $(id).removeClass("hiddenLink");
        $(id).parent().attr("href", np);
        pageCompletionSequence = "1";
    }
}

function elementRestore(id) {
    $(id).addClass("hiddenLink");
    $(id).parent().removeAttr("href");
}

1 个答案:

答案 0 :(得分:1)

此插件具有针对此案例的事件回调。

$("#likesTags").tagit({
    //This should be appended to your current tagit initializing call.
    afterTagAdded: function() {
        onTagsUpdated('#likesTags');
    },
    afterTagRemoved: function() {
        onTagsUpdated('#likesTags');
    }
});

function onTagsUpdated(id){
    var tags = $(id).tagit("assignedTags"); //Returns an array of the text values of all the tags currently in the widget.
    console.log('tags of',id,'updated:',tags);
}